Overflowing remainder calculation in C++ [duplicate] - c++

This question already has answers here:
Why is my integer math with std::pow giving the wrong answer?
(5 answers)
Calculating (a^b)%MOD
(7 answers)
Closed 10 months ago.
I want to calculate the below expression:
pow(2012, 17) % 3569
When I do this in Ruby like this, it shows 915.
print (2012 ** 17) % 3569
When I do this in C++ like this, it shows 1190.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << remainder(pow(2012, 17), 3569) << endl;
}
915 looks correct.
Why are they different and how to fix the C++ code?

Thanks to Goswin, I could rewrite the C++ code like this
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int result = 1;
for (int i = 0; i < 17; i++) {
result *= 2012;
result = result % 3569;
}
cout << result << endl;
}
Now it works. Thank you.

Why are they different
Because C++'s pow does floating-point rather than integer math.
In exact integer arithmetic, pow(2012, 17) would be 145,102,735,039,632,235,424,933,403,463,510,202,882,323,568,682,170,580,992. But the standard IEEE 754 double can only approximate this value as 1.4510273503963223e+56, or to be ultra-precise, 145,102,735,039,632,225,543,927,922,730,425,249,428,937,718,149,261,819,904, with only the first 16 sig figs correct. Taking this number modulo 3569 gives 1190, as you have seen.
To get the expected result of 915, you need to use integer arithmetic. I don't think the standard C++ library has a function for that, but it's easy to implement one. Here's a recursive version:
int powmod(int base, int exponent, int modulus)
{
if (exponent == 0)
{
return 1;
}
else if (exponent % 2 == 0)
{
int square_root = powmod(base, exponent / 2, modulus);
return square_root * square_root % modulus;
}
else
{
return powmod(base, exponent - 1, modulus) * base % modulus;
}
}
The else if (exponent % 2 == 0) special-casing of even exponents isn't required, but allows the algorithm to run in logarithmic rather than linear time.

Related

Number of permutations calculation in c++ [duplicate]

This question already has answers here:
What is the behavior of integer division?
(6 answers)
Closed 6 months ago.
I am learning c++ and having a bit of trouble with my homework.
We have to write code using the double variable type and use two variables to calculate the number of permutations of the potential team arrangements…
The question specifies that there are 18 people in the group and you want to divide the group into teams of 3 members.
This is my current code:
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
int fact(int n) {
if (n == 0) return 1;
if (n > 0) return n * fact(n - 1);
}
int main()
{
double n = 18.0;
double r = 3.0;
double answer = fact(n) / (fact(r) * fact(n - r));
cout << “The number of arrangements = “ << answer << endl;
system(“pause”);
return 0;
}
When I run the code I am receiving “The number of arrangements = 1”
This is not the correct answer. Can someone please help me figure out what I am doing wrong?
Thanks!
Your fact function is returning an int, not a double.
Since your factorial function is returning an int, fact(n) is an int, and fact(r) * fact(n - r) is also an int.
Together, they will perform integer division, i.e. floor division, not true division.
Edit: Looked at the code again, I realized the problem wasn't integer division, it was the fact that int overflowed, where as double wouldn't overflow until 171!.

Difference between x * 0.1 and x / 10?

I am a high school student and I saw a while ago that is better to multiply than to divide. Since then, without any proof found that it is true or not and without knowing how to do find it by myself at the moment, I tried to modify my codes for that slightly better time.
Here is a problem where I wanted to find the biggest digit in a number using recursion.
This one is working.
#include <iostream>
using namespace std;
int minn = 9;
int digit(int n)
{
if(minn > n % 10)
minn = n % 10;
if(!(n / 10))
return minn;
else
return digit(n / 10);
}
int main()
{
int x;
cin >> x;
cout << digit(x);
return 0;
}
But this is not working.
#include <iostream>
using namespace std;
int minn = 9;
int digit(int n)
{
if(minn > n % 10)
minn = n % 10;
if(!(n * 0.1))
return minn;
else
return digit(n / 10);
}
int main()
{
int x;
cin >> x;
cout << digit(x);
return 0;
}
The only difference is that the broken one use if(!(n * 0.1)) not if(!(n / 10)).
Can someone clarify it for me or anyone who is seeking help what is the difference between x * 0.1 and x / 10?
Thank you all for clicking the question and that you tried to help!
0.1 is a double type, 10 is an integer type.
When dividing two integers e.g. n / 10 you will get integer division (e.g. 6/10 will equal 0).
And your check will work differently when using 6 * 0.1 as that will equal 0.6.
n * .1 results in a floating point result. So, 3 * .1 produces the result of .3, which is definitely not 0.
On the other hand, 3/10 is 0. That's how integer division works in C++.
You define x as int, x*0.1 uses float arithmetics, while x/10 uses integer arithmetics
Can someone clarify it for me or anyone who is seeking help what is the difference between x * 0.1 and x / 10?
Difference is very significant. In the first case you use floating point multiplication in the second integer division. So first if() would happen when n == 0 while second when n < 10.
if( !(n*0.1) ) // for if to work result of n * 0.1 must be equal 0 which only happens when n == 0
if( !(n/10) ) // for if to work result of n / 10 must be equal to 0 which happens when abs(n) < 10 (including 0)

boost::multiprecision: What's the cheapest way to multiply or divide by a huge power of 10? Something like bitshift op for powers of 10?

Consider the following MCVE:
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
int main()
{
boost::multiprecision::cpp_int x = 10;
x *= 10000000000000000000000000000000000000000000000000000000000000;
std::cout<<x<<std::endl;
return 0;
}
It produces a wrong result, due to the obvious overflow from that int. How can I do this correctly, assuming I don't want to involve strings? Is there something like a "digit shift operator" or a power function that can do this cheaply (or cheapest possible)?
Why? Because I have a fixed-precision library that I wrote, and scaling the internal integer requires such operations to be 100% safe.
Find the example here.
You'll want a function to auto-generate the number you need.
boost::multiprecision::cpp_int pow(boost::multiprecision::cpp_int value, boost::multiprecision::cpp_int exponent) {
if(exponent <= 0)
return 1;
else if(exponent == 1)
return value;
else {
if(exponent % 2 == 0) {
return pow(value * value, exponent / 2);
} else {
return value * pow(value, exponent - 1);
}
}
}
int main()
{
boost::multiprecision::cpp_int x = 10;
x *= pow(10, 61);//I believe this is the correct number of 0's from manually counting
std::cout<<x<<std::endl;
return 0;
}
If boost.multiprecision has a baked in pow function (I couldn't find one), use that instead.

c++ why does ((1 / 2) * 2) return 0 [duplicate]

This question already has answers here:
Why does division result in zero instead of a decimal?
(5 answers)
Integer division always zero [duplicate]
(1 answer)
Closed 7 years ago.
first time I'v posted here but I must know what's wrong with this simple peace of code:
#include <iostream>
using namespace std;
int main()
{
double test = (1 / 2) * 2;
cout << test << endl;
return 0;
}
when ever I run this the code it displays 0, should I be casting something, it happens regardless of what compiler I use and it returns even stranger results if the '1' is divided be some form of decimal.
Because in integer maths 1 / 2 == 0 and 0 * 2 == 0.
Try with 1.0 and 2.0 instead.
In (1 / 2) both the 1 and 2 are integers which means that the result is also an integer. This means the expression returns 0. 0 * 2 is 0.
To get the result you want, try (1.0 / 2.0)
If you want to get right result you need to write:
#include <iostream>
using namespace std;
int main()
{
double test = ((double)1 / 2) * 2;
cout << test << endl;
return 0;
}
You're using int instead of double.
Fixing...
#include <iostream>
using namespace std;
int main()
{
double test = (1.0 / 2.0) * 2.0;
cout << test << endl;
return 0;
}

To Find Large Powers in C++ [duplicate]

This question already has answers here:
How to calculate modulus of large numbers?
(10 answers)
Closed 9 years ago.
I have two numbers A and B
where A and B can be in the range 1<= A,B <=100^100000
How can we find the value of A^B modulo some M in C++ ??
In the duplicate I pointed out, the solution I particularly like is https://stackoverflow.com/a/8972838/1967396 (see there for attribution and references)
For your convenience I reproduce the code here (wrapped into an SCCE - but using C, not C++):
#include <stdio.h>
int modular(int base, unsigned int exp, unsigned int mod)
{
int x = 1;
int i;
int power = base % mod;
for (i = 0; i < sizeof(int) * 8; i++) {
int least_sig_bit = 0x00000001 & (exp >> i);
if (least_sig_bit)
x = (x * power) % mod;
power = (power * power) % mod;
}
return x;
}
int main(void) {
printf("123^456mod567 = %d\n", modular(123, 456, 567));
}
Amazing, isn't it.
use the formula (a*b)mod m = (a*(b (mod m))) (mod m). For more details see the wiki page Modular exponentiation
Another solution assumes that your M is fixed (or at least that you need to compute A^B many times with the same M).
Step 1: compute the Euler's totient function (this requires a factorization of M, so it's quite expensive). Let's call this number k.
Due to the Fermat's little theorem, your answer is simply:
(a % M)^(b % k)
Now, unless M is a large prime number, this greatly simplify the problem.
The above problem can be solved using the code snippet below.
Thus to ensure this code does not overflow, check that n * n <= 2 ^ 31.
int modPow(int base, int exp, int n) {
base = base%n;
if (exp == 0)
return 1;
else if (exp == 1)
return base;
else if (exp%2 == 0)
return modPow(base*base%n, exp/2, n);
else
return base*modPow(base, exp-1, n)%n;
}