Pablo Marcos Pablo Marcos - 1 month ago 9
C Question

Division by 2 and infinite loop in C

I'm doing an implementation of the 3n+1 algorithm, but for some reason when n=2, the division n = n/2 doesn't change the value, creating an infinite loop, and I can't see why:

#include <stdio.h>
#include <stdlib.h>


int main(void)
{
int i=0,j=0,n=0,count,max;

scanf("%d",&i);
scanf("%d",&j);

max = 0;

for(n=i; n<=j; n++){
count = 0;

while(n != 1){
//Debug print
printf("%d - %d\n",count,n);

if(n%2 != 0){ //Odd
n = 3 * n + 1;
} else { //Even

n = n / 2;

//n /= 2;
//n = n >> 1;
}
count++;
}
max = (count > max) ? count : max;
}
printf("%d %d %d\n",i,j,max);

exit(EXIT_SUCCESS);
}


[Solve] The for loop and de while loop was changing the value of n

for(k=i; k<j;k++){
count =0;
n = k;
while( n!= 1){
. . .

Answer

It is changing n, and is exiting the while loop. However, the code that gets executed after that is responsible for the infinite loop.

If you can't use a debugger, try adding a printf statement right after count = 0 to see what is happening. Or, assuming that the while loop does exit with n=1 (which it does), what will happen to n when you start another iteration of the for loop?