Problem:
The radical of n, rad(n), is the product of distinct prime factors of n. For example, 504 = 23 [×] 32 [×] 7, so rad(504) = 2 [×] 3 [×] 7 = 42.
We shall define the triplet of positive integers (a, b, c) to be an abc-hit if:
1. GCD(a, b) = GCD(a, c) = GCD(b, c) = 1
2. a [<] b
3. a + b = c
4. rad(abc) [<] c
For example, (5, 27, 32) is an abc-hit, because:
1. GCD(5, 27) = GCD(5, 32) = GCD(27, 32) = 1
2. 5 [<] 27
3. 5 + 27 = 32
4. rad(4320) = 30 [<] 32
It turns out that abc-hits are quite rare and there are only thirty-one abc-hits for c [<] 1000, with [∑]c = 12523.
Find [∑]c for c [<] 120000.
We shall define the triplet of positive integers (a, b, c) to be an abc-hit if:
1. GCD(a, b) = GCD(a, c) = GCD(b, c) = 1
2. a [<] b
3. a + b = c
4. rad(abc) [<] c
For example, (5, 27, 32) is an abc-hit, because:
1. GCD(5, 27) = GCD(5, 32) = GCD(27, 32) = 1
2. 5 [<] 27
3. 5 + 27 = 32
4. rad(4320) = 30 [<] 32
It turns out that abc-hits are quite rare and there are only thirty-one abc-hits for c [<] 1000, with [∑]c = 12523.
Find [∑]c for c [<] 120000.
Solution:
-59231
Code:
The solution may include methods that will be found here: Library.java .
public interface EulerSolution{
public String run();
}
/*
* Solution to Project Euler problem 27
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p027 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p027().run());
}
public String run() {
int bestNum = 0;
int bestA = 0;
int bestB = 0;
for (int a = -1000; a <= 1000; a++) {
for (int b = -1000; b <= 1000; b++) {
int num = numberOfConsecutivePrimesGenerated(a, b);
if (num > bestNum) {
bestNum = num;
bestA = a;
bestB = b;
}
}
}
return Integer.toString(bestA * bestB);
}
private static int numberOfConsecutivePrimesGenerated(int a, int b) {
for (int i = 0; ; i++) {
int n = i * i + i * a + b;
if (n < 0 || !Library.isPrime(n))
return i;
}
}
}
No comments :
Post a Comment