c++pow

Output of pow() function in C++ is not giving accurate answer


The user will give an integer input. I have to find the mod after squaring it. But when I give a big integer, pow() gives the wrong answer. How can I fix that?

#include<bits/stdc++.h>

using namespace std;

int main()
{
    //ios_base:: sync_with_stdio(false);
    //cin.tie(NULL);
    int t;
    cin >> t;
    for(int i = 0; i < t; i++)
    {
        long long n;
        cin >> n;

        long long sn = 0;
        sn = pow(n, 2);
        long long v = pow(10, 9) + 7;

        cout << sn % v << endl;
    }
}

Solution

  • As the comments say, pow works on floating point numbers. Since you want to square integers, you're better off just multiplying them together using sn = n*n. If you use an unsigned long long you'll be able to exactly compute the square but only if this square is at most +18,446,744,073,709,551,615 (see https://en.m.wikipedia.org/wiki/C_data_types)