Ex. 4-Basic programming Let the sequence (unlnze of integers be defined by uo =
ID: 3919867 • Letter: E
Question
Ex. 4-Basic programming Let the sequence (unlnze of integers be defined by uo = a Ui, if ui is even ui+1 3u 1 if u; is odd 1. Write a function which prompts the user for a and determines N such that UN 1 2. Write a function which prompts the user for a value M, and returns A, the value of 2 a M, such that N is maximized. Specifications Input: two lines, the first one being 1 or 2 for the function from question 1 or 2, respectively, and an integer corresponding to a or M on the second one; Output: one line showing the result;Explanation / Answer
//Question 1 In Java
public static void findN(){
Scanner S = new Scanner(System.in);
int a = S.nextInt();
try{
System.out.println(findNHelper(a,0));
}
catch(Exception e){
System.out.println("Error: StackOverflow");
}
}
public int findNHelper(int a, int n){
if(a==1){
return n;
}
if(n%2==0){
return findNHelper(a/2,n+1);
}
else{
return findNHelper(3*a+1,n+1);
}
}
//Though this is a way to solve thia via any code. But this question is limited to only a few value. And at other values it doesnt occur.
//Similarly for Question2 it occurs for the same values of Q1 and for the rest cause stack Overflow.
//Maybe there is a flaw in the question or there is lack of understanding by me. but i thought to inform u anyway
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.