Problem 17

Statement
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

Solution
The code, in C.

#include <stdio.h>

int main(void)
{
  int i,j,a,b;
  long long int n=0;
  int nb1[20] = {0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,8,8};
  int nb2[10] = {0,0,6,6,5,5,5,7,6,6};
  for(i=1;i<=1000;i++){
    a=0;
    j=i%100;
    if(j<20)
      a+=nb1[j];
    else{
      a+=nb1[j%10];
      a+=nb2[j/10];
    }
    b=0;
    j=i/100;
    if(j!=0){
      if(a!=0)
	b+=3;
      if(j%10)
	b+=7;
      if(j/10)
	b+=8;
      b+=nb1[j%10];
      b+=nb1[j/10];
    }
    n+=(a+b);
  }
  printf("%lld\n",n);
  return 0;
}

Answer
21124

No tags for this post.

SPEAK / ADD YOUR COMMENT
Comments are moderated.

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>