Suppose we start with a positive integer x, and repeatedly apply the rules . If
ID: 663338 • Letter: S
Question
Suppose we start with a positive integer x, and repeatedly apply the rules . If x is even, then divide it by 2. . If x is odd, then multiply it by 3 and add 1. stopping when x reaches 1. For example, if we start with 17, then we get the sequence of numbers: (a) Write a method public int numSteps(int x) that calculates the sequence starting at x and returns the number of steps it takes to reach 1. For example, numSteps(17) should return the value 12, because it takes 12 steps for the sequence starting at 17 to reach 1. (6 marks) (b) Write a method that will allow the user to determine which positive integer less than or equal to 10000 gives the longest sequence. (You must specify both the method signature and its implementation.)Explanation / Answer
a) public int numSteps(int x)
{
int count=0;
while(x!=1)
{
if(x%2==0)
{
x=x/2;
count++;
}
else
{
x=x*3;
x=x+1;
count++;
}
}
return count;
}