For any greater than1The natural numberNnn 3n+1n After several such transformations, it is certain that n13→10→5→16→8→4→2→1 Enter nn≤109 Sample Input:
3 sample
Example Output:
7
1#include <iostream>2#include <iomanip>3#include <cmath>4 using namespacestd;5 6 intMain ()7 {8 intn;9CIN >>n;Ten intCount =0; one while(n! =1) a { - if(n%2==0) - { then = n/2; - - } - Else + { -n =3* n +1; + a } atcount++; - } -cout << Count <<endl; -System"Pause"); - return 0; -}
For example, The result can be output correctly, but when you enter 987654321, you cannot output the correct Result. The size of int should be-2147483648-2147483647, which is beyond the range of int, and the type of n is defined as long long, so you can output 180 directly.
1#include <iostream>2#include <iomanip>3#include <cmath>4 using namespacestd;5 6 intMain ()7 {8 Long Longn;9CIN >>n;Ten intCount =0; one while(n! =1) a { - if(n%2==0) - { then = n/2; - - } - Else + { -n =3* n +1; + a } atcount++; - } -cout << Count <<endl; -System"Pause"); - return 0; -}
An example of an int range (algorithmic Race Primer Classic)