Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created December 15, 2017 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/f7076ba47d733ed6172fb1b70b077aa6 to your computer and use it in GitHub Desktop.
Save jianminchen/f7076ba47d733ed6172fb1b70b077aa6 to your computer and use it in GitHub Desktop.
Calculate steps to reach 1 ? Need to look up Google and find the similar problem.
/*
Problem statement:
f(n) = { 3n + 1 if n is odd
{ n/2 if n is even
Given n value 3, it will take 8 steps to reach 1. (?)
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment