普通循环代码(c语言)
size_t treeN (size_t i) { if (i < 1) { return 0; } size_t num = 1; size_t n = i; printf("%d ",n); while (n != 1) { if (n % 2 == 0) { n = n / 2 ; }else { n = 3 * n + 1; } num ++; printf("%d ",n); } return num; }
数组递归调用
size_t treeN2(int* p,int n) { int* position = p; size_t L = 1; int number = n; while (number >= n) { if (number % 2 == 0) { number = number / 2; }else { number = number * 3 + 1; } L++; } if (*(p+number) == 0) { if (number % 2 == 0) { *(p+number) = treeN2(p,number/2) + L; }else { *(p+number) = treeN2(p,number * 3 + 1) + L; } } return *(p+number); }
主函数
int main() { int res1 = treeN(100); int a[100] = {0}; //先创建一个所求数大小的数组 a[1] = 1; // 将1位置初始化为1 int res2 = treeN2(a,100) + 1; return 0; }