Large non-Mersenne prime
The first known prime found to exceed one million digits was discovered in 1999, and is a Mersenne prime of the form ; it contains exactly digits. Subsequently other Mersenne primes, of the form , have been found which contain more digits.
However, in 2004 there was found a massive non-Mersenne prime which contains digits: .
Find the last ten digits of this prime number.
Implementations
#include <iostream>
long long mod_pow(long long base, long long exp, long long mod) { long long result = 1; base %= mod; while (exp > 0) { if (exp % 2 == 1) { // Use __int128 to avoid overflow in multiplication __int128 temp = (__int128)result * base % mod; result = temp; } __int128 temp_base = (__int128)base * base % mod; base = temp_base; exp /= 2; } return result;}
long long large_non_mersenne_prime() { const long long MOD = 10000000000LL; // 10^10 long long pow2 = mod_pow(2, 7830457, MOD); // Use __int128 for the final multiplication to avoid overflow __int128 temp = (__int128)28433LL * pow2 % MOD; long long result = (temp + 1) % MOD; return result;}Solution Notes
Mathematical Background
The problem requires finding the last 10 digits of a very large number: 28433 × 2^7830457 + 1. Direct computation is impossible due to the number’s size, so modular arithmetic is used.
Algorithm Analysis
Compute 2^7830457 mod 10^10 using fast modular exponentiation (O(log exponent)), then multiply by 28433 mod 10^10, add 1, and take mod 10^10 again.
Performance
Extremely fast (~1ms) across all languages due to logarithmic time complexity and small modulus.
Key Insights
- Modular exponentiation prevents overflow by taking remainders at each step
- Big integer libraries needed in some languages for intermediate calculations
- Last digits computation reduces huge number to manageable arithmetic
Educational Value
Demonstrates modular arithmetic applications, fast exponentiation algorithms, and handling very large numbers in programming.
Problem #97 is taken from Project Euler and licensed under CC BY-NC-SA 4.0.