I am trying to solve a programming problem in c (version : (MinGW.org GCC Build-2) 9.2.0)
I am using modulo operator to give answer in int range but for 6 ,it is giving me -ve answer
why is this happening??
my code :
#include <cmath>
#include <iostream>
using namespace std;
int balancedBTs(int h) {
if (h <= 1) return 1;
int x = balancedBTs(h - 1);
int y = balancedBTs(h - 2);
int mod = (int)(pow(10, 9) 7);
int temp1 = (int)(((long)(x) * x) % mod);
int temp2 = (int)((2 * (long)(x) * y) % mod);
int ans = (temp1 temp2) % mod;
return ans;
}
int main()
{
int h;
cin >> h;
cout << balancedBTs(h) << endl;
return 0;
}
CodePudding user response:
The code makes two implicit assumptions:
- int is at least 32 bit (otherwise the 1,000,000,007 for mod will not fit)
- long is bigger than int (to avoid overflows in the multiplication)
Neither of these assumptions are guarantee by the standard https://en.cppreference.com/w/cpp/language/types
I don't have access to the same platform in the question, but I can reproduce the output exactly if I remove the cast to long in the assignment of temp1 and temp2 (effectively simulating a platform were sizeof int and long is both 4).
You can verify if the second assumptions hold in your platform checking the sizeof(int) and sizeof(long).
CodePudding user response:
if you try int ans = (temp1 temp2 mod) % mod; this will give you the positive congruent to any negative answer in modulo mod and will not affect the positive answers
as a counter example : -2 ≡ (-2 5) ≡ 3 (modulo 5) , 3 ≡ (3 5) ≡ 3 (modulo 5)