Reputation: 426
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;
}
Upvotes: 1
Views: 148
Reputation: 3978
The code makes two implicit assumptions:
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).
Upvotes: 1