这是我在 Java 上模拟 Collatz 猜想的程序:
import java.util.*;
public class Collatz {
public static void main(String args[]){
Scanner raj= new Scanner(System.in);
int n;
int k=0;
System.out.print("n? ");
n = raj.nextInt();
while(n > 1){
if(n%2 ==1){
n=3*n+1;
System.out.println(n);
k++;
}
if(n%2==0){
n=n/2;
System.out.println(n);
k++;
}
}
System.out.print("It took " + k + " iterations!");
}
}
Run Code Online (Sandbox Code Playgroud)
当我输入 n=6 时,我得到
3 10 5 16 8 4 2 1 迭代了 8 次!
但是当我输入 n= 63728127 时,我得到
191184382 95592191 286776574 143388287 430164862 215082431 645247294 322623647 …