Harini :
Get the number n from the user.Then print the nth number that has at-least 4 distinct prime factors. Eg(210 prime factors(2,3,5,7) ) 210 is the first number that is having 4 distinct prime factors the next number is 330(2,3,5,11). Input:2 output:330 and Input:3 output:390.I don't know how to do this?I tried to find the prime factors for a number.
for (int i = 2; i <= number; i++) {
while (number % i == 0) {
System.out.print(i + " ");
number = number / i;
}
}
if (number < 1)
System.out.println(number);
But i want to print the nth number that has 4 distinct prime factors.
Nicholas K :
You may use the following code:
public static boolean findPrimeFactors(int n) {
Set<Integer> primeFactorSet = new HashSet<>();
while (n % 2 == 0) {
// here number is even so adding 2
primeFactorSet.add(2);
n /= 2;
}
// number would be odd in this loop
for (int i = 3; i <= Math.sqrt(n); i += 2) {
while (n % i == 0) {
primeFactorSet.add(i);
n /= i;
}
}
if (n > 2) {
primeFactorSet.add(n);
}
// true if the unique prime-factors are greater than or equal to 4
return primeFactorSet.size() >= 4 ? true : false;
}
Now invoke it using:
public static void main(String[] args) {
List<Integer> primeFactorList = new ArrayList<Integer>();
// accept this from user
int n = 2;
for (int i = 210;; i++) {
// find prime factors for each number
if (findPrimeFactors(i)) {
primeFactorList.add(i);
}
if (primeFactorList.size() == n) {
System.out.println(primeFactorList.get(n - 1));
break;
}
}
}
Explanation:
- The loop iterates from 210 till the nth number that has four or more different prime factors.
- For every number that meets the criteria, the method returns true else false.
- Next a check is made to see if the size of the list is equal to the number (
n
) entered by the user. If its equal then-1
th index is fetched and the loop is exited.