2.Suppose that the first number of a sequence is x, where x is an integer. Define a^0 = x; a^n+1 = 𝒂^𝒏/ 𝟐 if an is even; a^n+1 = 3a^n + 1 if an is odd. Then there exists an integer k such that a^k = 1. Write a program that prompts the user to input the value of x. The program outputs the integer k such that a^k = 1 and the numbers a^0, a^1, a^2,…a^k. (For example, if x = 75, then k = 14, and the numbers a^0, a^1, a^2,…ak, respectively, are 75, 226, 113, 340, 170, 85, 256, 128, 64, 32, 16, 8, 4, 2, 1. (Test your program for the following values of x : 75, 111, 678, 732, 873, 2048, and 65535)
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int x,y,z,k,a=1,s;
System.out.println("enter the value of x");
x=input.nextInt();
System.out.println("enter the value of k:");
k=input.nextInt();
System.out.print(x+",");
for(;a<=k;a++)
{
y=x%2;
if(y==0)
{
x=x/2;
}
else
{
x=3*(x+1);
x=x-2;
}
System.out.print(x+",");
}
}
}
sample output:
enter the value of x
75
enter the value of k
14
75,226,113,340,170,85,256,128,64,32,16,8,4,2,1,
Comments
Leave a comment