Skip to content

Instantly share code, notes, and snippets.

@jakedobkin
Created November 18, 2011 05:38
Show Gist options
  • Select an option

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

Select an option

Save jakedobkin/1375704 to your computer and use it in GitHub Desktop.
Euler 17
#!/usr/local/bin/node
// first we need to declare a few arrays to hold the names
ones = ["", "one","two","three","four","five","six","seven","eight","nine", "ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"]
twenties = ["","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"]
sum = 0;
// for loop to extract each number, turn it into a string, slice it into digits
for (i=1000;i>=1;i--)
{
number = i.toString();
a = number.substr(number.length-1, 1);
if (number.length>=2) {b = Number(number.substr(number.length-2, 1));} else {b = 0;}
if (number.length>=3) {c = Number(number.substr(number.length-3, 1));} else {c = 0;}
if (number.length>=4) {d = Number(number.substr(number.length-4, 1));} else {d = 0;}
// now let's turn the digits into words- paying special attention to the AND and numbers 1 to 19
if (d>0) { thousands = ones[d] + "thousand";} else {thousands = "";}
if (c>0) { hundreds = ones[c] + "hundred";} else {hundreds = "";}
if (c>0 && (b>0 || a>0)) { and = "and";} else {and = "";}
if (b>1) { tens = twenties[b] + ones[a];}
else if (b==0 || b==1) { tens = ones[Number(b.toString() + a.toString())];}
else {tens="";}
// now let's add up all those letters
// console.log("i is " + i + " which is " + thousands + hundreds + and + tens);
sum += thousands.length + hundreds.length + and.length + tens.length;
}
console.log("sum is " + sum + " letters");
@jakedobkin
Copy link
Author

This was just an annoying process- mostly because of all the switching between numbers and strings, and having to figure out the special cases. I'm sure there's a more efficient way to do it.

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