Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
What is the need of the statement of (num+mod)%mod?

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;
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!