-5
long long fast_exp(long long int base,long long int exp,int p) {
int res=1;
while(exp>0) {
if(exp%2==1)
{res=(res*base)%p;}
exp=exp>>1;
base=(base*base)%p;

}
return res;
}

It is a function of modular exponentiation. I want to ask about this while loop. When does this loop terminate? Because exp is always greater than 0. I also don't understand this loop in that how it run and how it works line by line. I don't understand the approach of this loop.

iBug
  • 30,581
  • 7
  • 64
  • 105
kk_00
  • 1
  • 3
  • If you want to know how it works *line by line*, use a debugger and step through the code line by line. This is not a tutorial site. – Ken White Nov 26 '17 at 04:55
  • 3
    [I downvoted because you don't appear to have made any effort to debug this yourself](http://idownvotedbecau.se/nodebugging/), and because the question's unclear. – EJoshuaS - Reinstate Monica Nov 26 '17 at 04:56
  • Perhaps you should take some time to [learn how to debug your programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)? – Some programmer dude Nov 26 '17 at 04:57
  • Spend some time thinking about what `exp = exp >> 1;` does. And remember from maths class that the 2k:th power is the square of the k:th power,. – molbdnilo Nov 26 '17 at 05:00
  • *Please*, indent your code and use one [indenting style](https://en.wikipedia.org/wiki/Indent_style) consistently throughout your code. Doing so makes it **much** easier to read/maintain. Doing so for code you place on Stack Overflow makes it much more likely both that users will up-vote your posts and that people will put time into Answering your Questions. It doesn't really matter which style your choose (although, for some languages, some styles are more appropriate than others). But, *pick one* and *use it consistently* for all code in a single project. – Makyen Nov 26 '17 at 05:24

1 Answers1

1

First you should format your code or it reads badly.

long long fast_exp(long long int base, long long int exp, int p) {
    int res = 1;
    while (exp > 0) {
        if (exp % 2 == 1) {
            res = (res * base) % p;
        }
        exp = exp >> 1;  // Note
        base = (base * base) % p;
    }
    return res;
}

Note the line with a comment. exp right shifts by 1 every iteration of the loop, so it'll eventually reach zero, terminating the loop.

I think Wikipedia explains this algorithm well so I don't have to repeat it. The pseudocode that Wikipedia shows is almost exactly the same as your code. Just compare them line-by-line.

There are also a few mistakes here:

  • The modulus is given as int p, which should have been long long p
  • The return value is int res, which should have been long long res
iBug
  • 30,581
  • 7
  • 64
  • 105