Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project Euler 97

Tags:

java

I'm trying to solve the Project Euler #97 problem. I don't want to look on the web because they give directly the solution.

Here's the exercise :

The first known prime found to exceed one million digits was discovered in 1999, and is a Mersenne prime of the form 2^6972593−1; it contains exactly 2,098,960 digits. Subsequently other Mersenne primes, of the form 2^p−1, have been found which contain more digits.

However, in 2004 there was found a massive non-Mersenne prime which contains 2,357,207 digits: 28433×2^7830457+1.

Find the last ten digits of this prime number.

So, I tried this :

public static void main(String []args){ 
        BigInteger i = new BigInteger("28433")
                          .multiply(new BigInteger(String.valueOf(Math.pow(2, 7830457)))
                          .add(new BigInteger("1")));
        
        String s = i.toString();
        System.out.println(s.substring(s.length()-10, s.length()));
     }

Obviously that does not work :

Exception in thread "main" java.lang.NumberFormatException: For input string: "Infinity"

How should I approach this problem (I'm really stuck) ? (please don't give the solution, just hints)

Thanks

like image 469
user2336315 Avatar asked Dec 18 '13 20:12

user2336315


1 Answers

You have a problem where you want the answer mod 10^10 (the last ten digits)

You can calculate powers faster by using powers of two. e.g. x*x = x^2, and x^2 * x^2 = x^4 and so on. 7 830 457 = 0b11101110111101110111001 is 2^23 + 2^22 + 2^21 + 2^19 ... 2^0 so it is x^(2^23) * x^(2^22) * x(2^21) * x ^(2^19) * ... x You have to perform each operation mod 10^10 to avoid overflow. You can the multiply this by the first constant and add 1.

Using this approach you can calculate in O(log N) where N is the power.

The key function which will do most of the work for you is BigInteger.modPow It is designed to calculate large powers efficiently but only calculating the lowest portion of a number (based on the mod chosen)

like image 169
Peter Lawrey Avatar answered Oct 17 '22 01:10

Peter Lawrey