-3

The other day I was solving one multiplication programming problem in which multiplicand(a1,a2,..an) can be 1<= ai <= 10^9 . So my question is how to multiply those numbers so that they'll always remain in (long long) range in C++.

Should I use any kind of mod(like 10^9+7) but it's not mentioned in question whether to use it or not?

I used normal multiplication with/without mod 10^9+7 only to vain. Also tried my luck with Russian Peasant Multiplication with mod 10^9+7

long long mulmod(long long a, long long b)
{
    long long res = 0; // Initialize result
    a = a % mod;
    while (b > 0)
    {
        // If b is odd, add 'a' to result
        if (b % 2 == 1)
            res = (res + a) % mod;

        // Multiply 'a' with 2
        a = (a * 2) % mod;

        // Divide b by 2
        b /= 2;
    }

    // Return result
    return (res % mod);
}

still no accepted solution. :-(

Edit 1: ll to long long.

SevenDante
  • 21
  • 3

1 Answers1

0

The solution could be either

  • Using wider integers (128+), which has already been solved: representing 128 bit numbers in c
  • Using floating point real numbers, where you lose accuracy in exchange of flexibility.
Community
  • 1
  • 1
Jorge Bellon
  • 2,901
  • 15
  • 25