Project Euler #97: Large non-Mersenne prime

Sort by

recency

|

26 Discussions

|

  • + 0 comments

    C++ Solution

    #include <bits/stdc++.h>
    #include <iomanip>
    using namespace std;
    typedef unsigned long long ULL;
    
    const unsigned __int128 MOD = 1000000000000ULL;
    
    unsigned __int128 Power(unsigned __int128 n, unsigned int e)
    {
        unsigned __int128 res = 1;
        
        while(e > 0)
        {
            if(e & 1) res = (res * n) % MOD;
            
            n = (n * n) % MOD;
            e >>= 1;
        }
        return res;
    }
    
    
    ULL sum = 0;
    bool DB = 0;
    
    int main() 
    {
        ios_base::sync_with_stdio(0);
        cin.tie(0);
        cout.tie(0);
        
        int t;
        cin >> t;
        
        while(t--)
        {   
            ULL a, b, c, d;
            cin >> a >> b >> c >> d;
            
            ULL val = (Power(b, c) * a + d) % MOD;        
            sum += val;
            sum %= MOD;
        }
        
        string ans = to_string(sum);
        
        if(ans.size() < 12) ans = string(12 - ans.size(), '0') + ans;
    
        cout << ans;
        
        return 0;
    }
    
  • + 0 comments

    Obviously many languages support a native solution to this problem; so if you want to challenge yourself, don't look up how it's implemented and perhaps try to come up with some version yourself. A little wikipedia-ing on large exponentiations gives many different implementations.

  • + 0 comments

    Sovled in Java 8 using BigInteger.modPow(BigInteger exponent, BigInteger m). Optimize the input, multiply/add/mod, use primitive long.

  • + 1 comment

    Incredibly easy in Python!

  • + 0 comments

    Lesson learned, read the output format properly. By the way, this problem is to a certain extent not as interesting as the original one, as we could play with mod cycle length in power of two, and is, as a result, not as dull as plug in this built-in method in this language and you are done, no need to care about why it works. I doubt if such approach is plausible for the general case. (Cycle Length of Power of Two)