Problem:
The first two consecutive numbers to have two distinct prime factors are:
14 = 2 [×] 7
15 = 3 [×] 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2² [×] 7 [×] 23
645 = 3 [×] 5 [×] 43
646 = 2 [×] 17 [×] 19.
Find the first four consecutive integers to have four distinct prime factors. What is the first of these numbers?
Solution:
134043
Code:
The solution may include methods that will be found here: Library.java .
public interface EulerSolution{
public String run();
}
/*
* Solution to Project Euler problem 47
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p047 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p047().run());
}
public String run() {
for (int i = 2; ; i++) {
if ( has4PrimeFactors(i + 0)
&& has4PrimeFactors(i + 1)
&& has4PrimeFactors(i + 2)
&& has4PrimeFactors(i + 3))
return Integer.toString(i);
}
}
private static boolean has4PrimeFactors(int n) {
return countDistinctPrimeFactors(n) == 4;
}
private static int countDistinctPrimeFactors(int n) {
int count = 0;
for (int i = 2, end = Library.sqrt(n); i <= end; i++) {
if (n % i == 0) {
do n /= i;
while (n % i == 0);
count++;
end = Library.sqrt(n);
}
}
if (n > 1)
count++;
return count;
}
}
No comments:
Post a Comment