【问题:3n+1问题】
猜想:对于任意大于1的自然数,若n为奇数,则将n变为3n+1,否则变为n的一半。经过若干次这样的变换,一定会使n变为1。例如3→10→5→16→8→4→2→1。
输入n,输出变换的次数。n≤109。
样例输入:3
样例输出:7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <stdio.h> int main() { int n, c; scanf("%d", &n); c = 0; while(n > 1) { if (n%2==1) n = n*3+1; else n = n / 2; c++; } printf("%d\n", c); return 0; } |
for 语句是一种循环语句,它是对 while 语句的推广,与while 语句比较,就会发现 for 语句的操作更直观一些。
1 2 3 4 5 6 7 8 9 10 11 12 | #include <stdio.h> int main() { int n, c; scanf("%d", &n); for(c=0; n > 1; c++) { if (n%2==1) n = n*3+1; else n = n / 2; } printf("%d\n", c); return 0; } |
for 语句的基本结构 for (初始化; 比较; 调整)