B1001 killed attractiveness of the (3n + 1) guess

Title Description

n is odd, the (3n + 1) cut by half; -> i.e., (3n + 1) / 2
where n is an even number, the n halved; -> i.e., n / 2
test any positive integer not exceeding 1,000 n, how many steps to get n = 1?

Precautions

There is a problem: int n, count = 1111;
this sentence is to make its meaning and n are equal to 1111 count it?
A: Wrong. n can be any number, but the count = 1111.
Here Insert Picture Description
Here Insert Picture Description

Problem-solving Code

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

int main()
{
   int n,count=0;
   scanf("%d",&n);
   while(n!=1)
   {
       if(n%2==0)
       {
           n=n/2;
           count++;
       }
       else
       {
           n=(3*n+1)/2;
           count++;
       }
   }
   printf("%d",count);
   return 0;
}

Improve:

The original approach:
it is determined that even after the assignment to n n / 2, count ++, or else as odd, 3n + 1 to n assignment in the if, count ++ once.
The improved:
the parity is determined in the if-else, count ++.

while(n!=1)
   {
       if(n%2==0)
       {
           n=n/2; 
       }
       else
       {
           n=(3*n+1)/2;
       }
       count++;
   }
Released eight original articles · won praise 0 · Views 290

Guess you like

Origin blog.csdn.net/qq_40733888/article/details/103979042