-3

In my code I am trying to multiply two numbers. The algorithm is simple as (k)*(k-1)^n. I stored the product (k-1)^n in variable p1 and then I multiply it with k. For n=10, k=10 (k-1)^n-1 should be 387420489 and I got this in variable p1 but on multiplying it with k, I get a negative number. I used modulus but instead of 3874208490, I get some other large positive number. What is the correct approach?

#include <iostream>

using namespace std;

typedef long long ll;

ll big = 1000000000 + 7;

ll multiply(ll a, ll b)
{
    ll ans = 1;
    for (int i = 1; i <= b; i++)
        ans = ans * a;
    return ans % big;
}

int main()
{
    int t;
    scanf("%d", &t);
    while (t--)
    {
        ll n, k;
        cin >> n >> k;
        ll p1 = multiply(k - 1, n - 1);
        cout << p1 << endl; // this gives correct value
        ll p2 = (k % big) * (p1 % big);
        cout << ((p2 + big) % big) % big << endl;
    }
}
greybeard
  • 2,249
  • 8
  • 30
  • 66
satyajeet jha
  • 163
  • 3
  • 12
  • 3
    Please use proper indentation – MIbrah Apr 05 '16 at 21:37
  • 1
    `i used modulous` - use a spelling checker, and modulus more often. – greybeard Apr 05 '16 at 21:38
  • 1
    Sadly this looks like jump on satya day. You have macroed or typedeffed and variable-named your code into near unreadability. Bad idea if you plan a career in software development, and you'll have to try harder if you want to win at a code obfuscation competition. – user4581301 Apr 05 '16 at 21:45
  • @FredLarson amazing how much your edit looks like the one I was about to post. – user4581301 Apr 05 '16 at 21:50
  • @user4581301 ijust need to learn this to solve one programming contest problem – satyajeet jha Apr 05 '16 at 21:50
  • Seems to work just fine if you get rid of `% big` and `+ big` everywhere. Why is it there? – Fred Larson Apr 05 '16 at 22:01
  • Recommendation: Fire up your development environment's debugger and start stepping through the code. Pay attention to the variables. When they change to values that they shouldn't, you've just stepped over a bug. – user4581301 Apr 06 '16 at 01:27

2 Answers2

0

What is ll type? If it is just int (and I pretty sure it is), it gets overflowed, because 32-bit signed type can't store values more than (2^31)-1, which approximately equals to 2 * 10^9. You can use long long int to make it work, then your code will work with the results less than 2^63.

Victor
  • 418
  • 2
  • 10
0

It's not surprising you get an overflow. I plugged your equation into wolfram alpha, fixing n at 10 and iterating over k from 0 to 100.

The curve gets very vertical, very quickly at around k = 80.

10^21 requires 70 binary bits to represent it, and you only have 63 in a long long.

You're going to have to decide what the limits of this algorithm's parameters are and pick data types corresponding. Perhaps a double would be more suitable?

link to plot is here

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142