What is the need of the statement ans = (ans + mod) % mod in this program ?
Assume that mod = 10^9+7. This function is computing a to the power of b under mod operation in O(log(n)) complexity:
long long power(long long a, long long b)
{
if (b == 0)
return 1ll;
long long ans = power(a, b/2);
ans = (ans * ans) % mod;
ans = (ans + mod) % mod;
if(b % 2 == 1)
ans = (ans * a) % mod;
ans = (ans + mod) % mod;
return ans;
}
The most common usage of such a construct is to make sure the result is non-negative. The standard operator% behaves differently for positive and negative arguments: for example, 4%3==1, but (-2)%3==-2, while you might expect (-2)%3==1 and (-2)/3==-1, which is mathematically more correct.
This behavior can often cause problems when modular arithmetic is used, and this trick of adding mod is often employed to obtain the mathematically more correct non-negative result. Instead of simply writing a%b, if a can be negative, one writes (a%b+b)%b.
However, its usage in the code in your question is strange. In that case, it is easier to assume that a is positive before calling the power function from the main code (for example, by making the main call like power((a%mod+mod)%mod, b)). Probably the author just wanted to get additional assurance of correctness, although it was not needed.
Related
I am currently practicing algorithms and DS. I have stumbled upon a question that I can't figure out how to solve. So the question's link is there:
In summary, it says that there is a number of chairs in a circle, and the position of the person (relative to a certain chair), and how many M movements he should make.
So the input is as following:
3 integer numbers N, M, X , The number of chairs, the number of times the boy should move and the first chair he will start from respectively ( 1 ≤ X ≤ N < 2^63 , 0 ≤ M < 2^63 )
So, what have I done so far? I thought about the following:
So I thought that the relative position after M movements is (x+m) % n, and since this can cause Integer overflow, I have done it like that, ((x%n) + (m%n)) % n. I have figured out that if the person has reached the last index of chair, it will be 0 so I handled that. However, it passes only 2 tests. I don't need any code to be written, I want to directed in the right way of thinking. Here is my code so far:
#include <iostream>
using namespace std;
int main() {
long long n, m, x;
cin >> n >> m >> x;
// After each move, he reaches (X+1).
// X, N chairs.
// ((X % N) + (M % N)) % N;
// Odd conideration.
if ( m % 2 == 1) {
m += 1;
}
long long position = (x % n + m % n) % n;
if (position == 0) {
position = n;
}
cout << position;
return 0;
}
If the question required specific error handling, it should have stated so (so don't feel bad).
In every real-world project, there should be a standard to dictate what to do with weird input. Do you throw? Do you output a warning? If so, does it have to be translated to the system language?
In the absence of such instructions I would err toward excluding these values after reading them. Print an error to std::cerr (or throw an exception). Do this as close to where you read them as possible.
For overflow detection, you can use the methods described here. Some may disagree, and for a lab-exercise, it's probably not important. However, there is a saying in computing "Garbage in == Garbage out". It's a good habit to check for garbage before processing, rather than attempting to "recycle" garbage as you process.
Here's the problem:
Say the value of N is 2^63-1, and X and M are both 2^63 - 2.
When your program runs untill the ((X % N) + (M % N)) % N part,
X % N evaluates into 2^63 - 2 (not changed), and so does M % N.
Then, the addition between the two results occurs, 2^63 - 2 + 2^63 - 2 there is the overflow happening.
After the comment of #WBuck, the answer is actually rather easy which is to change the long long to unsigned because there are no negative numbers and therefore, increase the MAX VALUE of long long (when using unsigned).
Thank you so much.
Edit: I’m a beginner to C++, and I’d like to understand more about how to optimize my code.
I have created a Fraction object in C++ as well as overloaded +, - operations etc. When I came to the unary operators, however, I realized I didn't know how to reduce the fraction in the most efficient manner. So I have a function gcd that finds the greatest divisor:
int gcd (int n, int m) {
int newN = n < 0 ? -n : n;
int newM = m < 0 ? -m : m;
if (newM <= newN && newN % newM == 0) { return newM; }
else if (newN < newM) { return gcd(newM, newN); }
else { return gcd(newM, newN%newM); }
}
and then I have an overloaded operator, for example, incrementation:
Fraction& Fraction::operator++() {
num = num + denom;
//reduce fraction
int divisor = gcd(denom,num);
num = num/divisor;
denom = denom/divisor;
if (num < 0 && denom < 0) {num *= (-1);}
if (denom < 0) {denom *= (-1);}
return *this;
}
For efficiency, I would like to put the reduce fraction part of the code in a separate single helper function so the final function would look like this:
Fraction& Fraction::operator++() {
num = num + denom;
//reduce fraction
reduce(num, denom);
return *this;
}
That way I don't have to copy and paste whatever is in //reduce fraction everytime I overload a unary operator for example. However, I'm not sure how the reduce(Fraction num, Fraction& denom) function should look like. At most I can implement it like this:
void reduce(int& num, int& denom) {
int divisor = gcd(denom,num);
num = num/divisor;
denom = denom/divisor;
if (num < 0 && denom < 0) {num *= (-1);}
if (denom < 0) {denom *= (-1);}
}
I'm sure the code above will run into issues during compilation, so I was wondering if I could be suggested any pointers as to efficiently create the reduce fraction function. This is maybe being a bit nitpicky since my original code runs fine, but since I am new to C++, I'd like to learn more about how I can make my code more efficient. Thanks a lot! Let me know if more information is needed.
Edit: The above code does not work. Compiles correctly, but does not reduce fraction properly. So 1/2 + 1/4 results in 6/8, not 3/4.
Well on a high level your gcd function is too complicated and the last part of reduce is a bit wrong. If only denom is negative you invert it.
Nicely shows why it's always a good idea to put code into proper functions because they can also be separately tested. So I'd suggest writing some unit tests for your reduce and gcd functions.
Start with a simple solution like
static int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
and adapt if needed for negative numbers considering % semantics. Thinking about it the function should already be fine like that and you just need to call std::abs(gcd(n,d)) in reduce.
In general you should ask yourself if you really want to pay the renormalization cost at every single operation or if you let the user decide when to call reduce.
For lower-level optimizations here are some hints:
Always test/measure, e.g. by looking at what the compiler actually produces with godbolt.org.
The recursion in gcd is not a problem from a performance point of view in this case as it's tail recursive and the compiler will turn it into a loop for you.
The out parameters in reduce are bad for optimizations cause the compiler has to prove they don't point to the same object. Returning a std::pair and using C++11 std::tie or C++17 structured bindings at the callsite if possible is way more elegant.
This question already has answers here:
Calculate a*a mod n without overflow
(5 answers)
Closed 7 years ago.
I have a code that contains statements like
ans =((ans % mod)*(n % mod)) % mod;
and,
inverse= findMMI_fermat(n,mod);
ans =((ans % mod)*(inverse % mod)) % mod;
findMMI_fermat is defined as:
ull fast_pow(ull base,ull n,ull M) //ull is unsigned long long
{
if(n==0)
return 1;
if(n==1)
return base;
ull halfn=fast_pow(base,n/2,M);
if(n%2==0)
return ( halfn * halfn ) % M;
else
return ( ( ( halfn * halfn ) % M ) * base ) % M;
}
ull findMMI_fermat(ull n,ull M)
{
return fast_pow(n,M-2,M);
}
All the variables are declared unsigned long long. The program is running fine till size of ans,mod and n all grow to the order of 10^18. I know that I can't multiply such large numbers directly and I know an approach of converting the integers to string and then multiplying them. But is there any other easier way?
No, there isn't. the other approach needs work too. but, does not use strings. it uses array of bytes or array of integers or long long.
But, it works exactly as the strings approach work.
Languages as Java have a built in library for big numbers. I don't recall such a library for c++.
In my short sports programming career i encountered many time Calculating mod of numbers like
26164615615665561165154564545......%(10000007)
I have done some research but could only find calculation of mods of numbers in the form
(a^b)%c
can anybody explain how to calculate mod of numbers like the first example.
C++ does not have any long integer arithmetic facilities as part of the standard library.
If you want to compute with long integers, you need to rely on an external library.
Two good choices seem to be
GMP: https://gmplib.org - if you are not afraid of C-like interface (there is also gmpxx though)
NTL: http://www.shoup.net/ntl/ - my personal favourite, provides clear and easy interface (e.g. class ZZ for long integers and ZZ_p for long integers modulo)
Here is an example (taken from NTL examples) of how a modular exponentiation could be done using NTL:
ZZ PowerMod(const ZZ& a, const ZZ& e, const ZZ& n)
{
if (e == 0) return ZZ(1);
long k = NumBits(e);
ZZ res;
res = 1;
for (long i = k-1; i >= 0; i--) {
res = (res*res) % n;
if (bit(e, i) == 1) res = (res*a) % n;
}
if (e < 0)
return InvMod(res, n);
else
return res;
}
I have found the solution(maybe)
So,here goes explaination.If we want to calculate mod of very big numbers that cannot be stored as any data type than we have to take number as a string.Than we will do something like this
int remainder(string &s,first)
{
int rem=0;
for(int i=0;i<s.length();++i)
rem=rem*10+(s[i]-'0');//Explaining this below
return rem;
}
Why does it work ?Take a paper and pen and start doing division of string with the number first(taking 100) for ease.
For example, for 1234 % 100.
1 mod 100 = 1
12 mod 100 =(1 * 10 + 2) mod 100 =12
123 mod 100 =(12 * 10 + 3) mod 100 =23
1234 mod 100 =(23 * 10 + 4) mod 100 =34
PS:This is my first answer.Sorry i wrote answer to my own question but i thought it would be good for future readers.
Let a, b be positive integers with different values. Is there any way to simplify these expressions:
bool foo(unsigned a, unsigned b)
{
if (a % 2 == 0)
return (b % 2) ^ (a < b); // Should I write "!=" instead of "^" ?
else
return ! ( (b % 2) ^ (a < b) ); // Should I write "(b % 2) == (a < b)"?
}
I am interpreting the returned value as a boolean.
How is it different from
(a%2)^(b%2)^(a<b)
which in turn is
((a^b)&1)^(a<b)
or, indeed
((a ^ b) & 1) != (a < b)
Edited to add: Thinking about it some more, this is just the xor of the first and last bits of (a-b) (if you use 2's complement), so there is probably a machine-specific ASM sequence which is faster, involving a rotate instruction.
As a rule of thumb, don't mix operators of different operator families. You are mixing relational/boolean operators with bitwise operators, and regular arithmetic.
This is what I think you are trying to do, I'm not sure, since I don't understand the purpose of your code: it is neither readable nor self-explaining.
bool result;
bool a_is_even = (a % 2) == 0;
bool b_is_even = (b % 2) == 0;
if (a_is_even == b_is_even) // both even or both odd
result = a < b;
else
result = a >= b;
return result;
I program in C# but I'd think about something like this:
return (a % 2 == 0) && ((b % 2) ^ (a < b))
Considering from you comments that '^' is equivalent to '=='
If you are returning a truth value, a boolean, then your proposed changes do not change the semantics of the code. That's because bitwise XOR, when used in a truth context, is the same as !=.
In my view your proposed changes make the code much easier to understand. Quite why the author thought bitwise XOR would be appropriate eludes me. I guess some people think that sort of coding is clever. I don't.
If you want to know the relative performance of the two versions, write a program and time the difference. I'd be surprised if you could measure any difference between them. And I'd be equally surprised if these lines of code were your performance bottleneck.
Since there is not much information around this issue, try this:
int temp = (b % 2) ^ (a < b);
if (a % 2 == 0)
return temp;
else
return !temp;
This should be less code if the compiler hasn't optimized it already.