-1

I have made a recursive function in c++ which deals with very large integers.

long long int findfirst(int level)
{
    if(level==1)
    return 1;
    else if(level%2==0)
    return (2*findfirst(--level));
    else
    return (2*findfirst(--level)-1);
}

when the input variable(level) is high,it reaches the limit of long long int and gives me wrong output. i want to print (output%mod) where mod is 10^9+7(^ is power) .

int main()
{
    long long int first = findfirst(143)%1000000007;
    cout << first;
}

It prints -194114669 .

Vaishal
  • 187
  • 1
  • 3
  • 15

2 Answers2

2

Normally online judges problem don't require the use of large integers (normally meaning almost always), if your solution need large integers probably is not the best solution to solve the problem.

Some notes about modular arithmetic

if a1 = b1 mod n and a2 = b2 mod n then:

a1 + a2 = b1 + b2 mod n
a1 - a2 = b1 - b2 mod n
a1 * a2 = b1 * b2 mod n

That mean that modular arithmetic is transitive (a + b * c) mod n could be calculated as (((b mod n) * (c mod n)) mod n + (a mod n)) mod n, I know there a lot of parenthesis and sub-expression but that is to avoid integer overflow as much as we can.

As long as I understand your program you don't need recursion at all:

#include <iostream>

using namespace std;

const long long int mod_value = 1000000007;

long long int findfirst(int level) {
    long long int res = 1;
    for (int lev = 1; lev <= level; lev++) {
        if (lev % 2 == 0)
            res = (2*res) % mod_value;
        else
            res = (2*res - 1) % mod_value;
    }
    return res;
}

int main() {
    for (int i = 1; i < 143; i++) {
        cout << findfirst(i) << endl;
    }
    return 0;
}

If you need to do recursion modify you solution to:

long long int findfirst(int level) {
    if (level == 1)
        return 1;
    else if (level % 2 == 0)
        return (2 * findfirst(--level)) % mod_value;
    else
        return (2 * findfirst(--level) - 1) % mod_value;
}

Where mod_value is the same as before:

Please make a good study of modular arithmetic and apply in the following online challenge (the reward of discovery the solution yourself is to high to let it go). Most of the online challenge has a mathematical background.

NetVipeC
  • 4,402
  • 1
  • 17
  • 19
1

If the problem is (as you say) it overflows long long int, then use an arbitrary precision Integer library. Examples are here.

Community
  • 1
  • 1
abligh
  • 24,573
  • 4
  • 47
  • 84