Click here to Skip to main content
15,889,176 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi i want to calculate the order of below code . but my problem is that i don't know how many times the loop executes in worse case?
can any one tell me that how many times this loop execute?
thanks
C++
while(n>0)
{
r=n%m;
n=m;
m=r;
}
Posted

Nobody can tell you: it's dependent on the input values.
If n == 0, it will run 0 times.
if n == 1000 and m == 10, it will fail with a divide by zero exception on the second pass.

We can't tell you a worse case for code that fails! :laugh:
 
Share this answer
 
Comments
CPallini 17-Oct-14 8:06am    
There is no division in the OP code.
OriginalGriff 17-Oct-14 8:17am    
*cough*
r=n%m;
*cough*

Technically, it's a remainder, but it throws divide-by-zero errors if you try 10 % 0 for example. Probably because it's often implemented with a divide!
CPallini 17-Oct-14 8:28am    
Yes, I've deleted my post.
Quote:
can any one tell me that how many times this loop execute?
On lucky scenarios, the following function tells you:
C
int how_many_times(int n, int m)
{
  int count = 0:
  while(n>0)
  {
    r=n%m;
    n=m;
    m=r;
    ++count;
  }
  return count;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900