Skip to content

Instantly share code, notes, and snippets.

@jakedobkin
Created November 16, 2011 18:54
Show Gist options
  • Select an option

  • Save jakedobkin/1370968 to your computer and use it in GitHub Desktop.

Select an option

Save jakedobkin/1370968 to your computer and use it in GitHub Desktop.
Euler 14
#!/usr/local/bin/node
// basic strategy is to run a for loop to check each number, and then run a while loop
// with some if statements to run each number down to 1 counting the steps.
biggesti = 0;
biggest = 0;
for(i=13;i<1000000; i++)
{
n = i;
steps=0;
while (n > 1)
{
if (n%2==0)
{
n = n/2;
steps+=1;
}
else
{
n = 3*n + 1;
steps+=1;
}
}
if (steps > biggest)
{
biggesti = i;
biggest = steps;
}
}
console.log(biggesti + " took " + biggest + " steps");
@jakedobkin
Copy link
Author

The first time I tried this, I used i inside the while statement, but it didn't work- I think maybe that messes up the way the for and while loops interact, but I'm not sure why. So I just stored i in a new variable called n before each while loop, and that seems to have worked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment