Write a Java program start with an integer n, divide n by 2 if n is even or multiply by 3 and add 1 if n is odd, repeat the process until n = 1
- برمجة جافا
- برمجة
- 2021-05-01
- razanmazen8711884270
الأجوبة
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int ctr = 0;
Scanner in = new Scanner(System.in);
int n = in.nextInt();
while (n != 1) {
System.out.println(n);
if (n % 2 == 0) {
n = n / 2;
ctr += 1;
}
else {
n = (3 * n + 1) / 2;
ctr += 1;
}
}
System.out.println(ctr);
in.close();
}
}
If input 5
Sample Output:
5 8 4 2 4
أسئلة مشابهة
القوائم الدراسية التي ينتمي لها السؤال