Project Euler > Problem 123 > Prime square remainders (Java Solution)

Problem:

Let pn be the nth prime: 2, 3, 5, 7, 11, ..., and let r be the remainder when (pn[−]1)n + (pn+1)n is divided by pn2.

For example, when n = 3, p3 = 5, and 43 + 63 = 280 [≡] 5 mod 25.

The least value of n for which the remainder first exceeds 109 is 7037.

Find the least value of n for which the remainder first exceeds 1010.


Solution:

4179871

Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
* Solution to Project Euler problem 23
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/


public final class p023 implements EulerSolution {

public static void main(String[] args) {
System.out.println(new p023().run());
}


private static final int LIMIT = 28123;

private boolean[] isAbundant = new boolean[LIMIT + 1];

public String run() {
// Compute look-up table
for (int i = 1; i < isAbundant.length; i++)
isAbundant[i] = isAbundant(i);

int sum = 0;
for (int i = 1; i <= LIMIT; i++) {
if (!isSumOf2Abundants(i))
sum += i;
}
return Integer.toString(sum);
}


private boolean isSumOf2Abundants(int n) {
for (int i = 0; i <= n; i++) {
if (isAbundant[i] && isAbundant[n - i])
return true;
}
return false;
}


private static boolean isAbundant(int n) {
if (n < 1)
throw new IllegalArgumentException();

int sum = 1; // Sum of factors less than n
int end = Library.sqrt(n);
for (int i = 2; i <= end; i++) {
if (n % i == 0)
sum += i + n / i;
}
if (end * end == n)
sum -= end;
return sum > n;
}

}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact