用递归解决的一道550分题

Problem Statement

The prime factorization of a number X is the list of prime numbers that multiply together to form X. For example,
the prime factorization of 12 is 2 * 2 * 3. Note that 1 is not a prime number.
An underprime is a number whose prime factorization contains a prime number of elements. For example, 12 is an
underprime because its prime factorization contains 3 elements, and 3 is a prime number. Given ints A and B, return
the number of underprimes between A and B, inclusive.
Definition

Class:
Underprimes
Method:
howMany
Parameters:
int, int
Returns:
int
Method signature:
int howMany(int A, int B)
(be sure your method is public)

Notes
-
A positive integer number is called prime if it has exactly two divisors - 1 and itself. For example, 2, 3, 5 and 7
are prime numbers, and 4, 6, 8 and 9 are not prime. By convention, 1 is not considered to be a prime number.
-
All prime factorizations of the same integer always contain the same prime numbers and can only differ by the order
of primes within them.
Constraints
-
A will be between 2 and 100000, inclusive.
-
B will be between A and 100000, inclusive.
Examples
0)


2
10
Returns: 5
The underprimes in this interval are: 4, 6, 8, 9, 10.
1)


100
105
Returns: 2
The underprimes in this interval are 102 = 2 * 3 * 17 and 105 = 3 * 5 * 7.
2)


17
17
Returns: 0
17 is a prime number, so its prime factorization contains one element. 1 is not a prime, so 17 is not an underprime.
3)


123
456
Returns: 217

 

问题是求给定的两个整数之间有多少个可以表示成素数个素数的乘积(真拗口)

代码关键是要对数字进行因数分解并判断因子本身及总数是否为素数,我用了递归来解决这个问题感觉还是蛮清晰的,对一个数字N从令i从2开始检验是否为N的因子,若是以N/i进入下一层,并随后跳出本次循环。对N=2的边界情况进行了预处理,代码如下:

 

 

public class Underprimes { public static int count = 0; public static int howMany(int A, int B) { int result = 0; for (int i = A; i <= B; i++) { count = 0; countUnderprime(i); if (isPrimes(count)) { result++; } } return result; } static boolean isPrimes(int nn) { if (nn == 1 || nn == 0) { return false; } for (int i = 2; i < nn; i++) { if (nn % i == 0) { return false; } } return true; } static void countUnderprime(int n) { if (n == 2) { count++; return; } int i = 1; while (i < n) { i++; if (n % i == 0 && isPrimes(i)) { count++; countUnderprime(n / i); break; } } } public static void main(String[] args) { int A = 123; int B = 456; System.out.println(howMany(A, B)); } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值