1. a) Write a function called collatz() that takes a number and checks whether i
ID: 3664058 • Letter: 1
Question
1. a) Write a function called collatz() that takes a number and checks whether it's even or odd. If it's even, the function should return half the number. If it's odd, it should return one more than three times the number. Remember to include a docstring with a purpose statement and signature for all of your function definitions.
b) If you keep repeating this process of taking the output of collatz() and feeding it back into the function, you'll eventually end up with 1. For example, collatz(2),collatz(collatz(4)), and collatz(collatz(collatz(collatz(collatz(5))))) all return 1. Play around with different numbers in the interactive shell like this until you find a number that requires at least 5 applications of collatz() before it gets down to 1. Make sure you do the repeated applications all in one line, like the examples I just listed.
Explanation / Answer
1) Write a function called collatz() :
static int collatz(int n) {
System.out.println(n);
if (n>1) {
if (n%2==0)
return (n/2);
else
return (3*n+1);
}
return n;
}
2) The number selected is 21
collatz(collatz(collatz(collatz(collatz(21)))))
output:
21
64
32
16
8
4
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.