Project Euler Problem 97 Solution

Project Euler Problem 97 Solution

Large Non-Mersenne prime

by {BetaProjects} | Project Euler & HackerRank
Difficulty: Hard

Project Euler Problem 97 Statement

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 \times 2^{7830457} + 1$.

Find the last ten digits of this prime number.

Solution

HackerRank Project Euler Problem 97 overview:

We are given a list $T$, $(1\le T\le 500,000)$ of4 integers, $A, B, C, D$ for the equation form $A\times B^C+D$ and need to find the last 12 digits of the sum of all numbers in the list.

Solution Summary

By using modular arithmetic and efficient exponentiation (pow() function) to calculate the last 12 digits of the large number without dealing with its full representation and keep a running sum. We print the 12-digit result with zero-fill.

Solution Detail
1. Initialization:
2. Input and Calculation:
3. Output:

Python Source Code

s = 0
m = 10**12
for _ in range(int(input())):
    a, b, c, d = map(int, input().split())
    s += (a * pow(b, c, m) + d) % m
print("%012d" % (s % m))