March 1, 2018
Introduction
I like to find some algorithm easy to solve and use it as the first mock interview algorithm.
The link is here.
Problem statement:
f(n) = 3n + 1 if n is odd or n/2 if n is even. Collapse sequence refers to each number according to this formula until the sequence becomes equal to 1. Find the number ( which is not greater than 10000), which will have the longest Collapse sequence.
For example:
3 > 10 > 5 > 16 > 8 > 4 > 2 > 1 = run length = 8
Problem solving
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Problem statement: | |
f(n) = 3n + 1 if n is odd or n/2 if n is even. Collapse sequence refers to each number | |
according to this formula until the sequence becomes equal to 1. Find the number ( which | |
is not greater than 10000), which will have the longest Collapse sequence. | |
3 > 10 > 5 > 16 > 8 > 4 > 2 > 1 = run length = 8 | |
*/ | |
public int getSteps(int n) { | |
if(n == 1) { | |
return 1; | |
} | |
return 1 + (n % 2 == 0) ? getSteps(n /2) : getSteps(3*n + 1); | |
} |
The next step is to write the calculation using recursive function. The first step to go over n = 3 takes 5 minutes, writing the recursive function takes another 5 minutes.
No comments:
Post a Comment