Solution to Problem 17 on ProjectEuler.net


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

The problem:

——-
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?

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of “and” when writing out numbers is in compliance with British usage.
——-

My solution:

#include

int main(){
int i,x,y,counter,fdigit;
int soma=0;
for (i=1;i<1001;i++){  
  if (i==10){
    soma+=3;
    continue;  
  }
  if (i==11||i==12){
    soma+=6;
    continue;  
  }
  if (i==13||i==14||i==18||i==19){
    soma+=8;
    continue;  
  }
  if (i==15||i==16){
    soma+=7;
    continue;  
  }
  if (i==17){
    soma+=9;
    continue;  
  }
  if (i==100||i==200||i==600){
    soma+=10;
    continue;  
  }
  if (i==300||i==800||i==700){
    soma+=12;
    continue;  
  }
  if (i==400||i==500||i==900||i==1000){
    soma+=11;
    continue;  
  }  
  x=i;
  counter=0;
  fdigit=0;
  while (x>0){  
    y=x%10;      
    if (counter==0){
      if (y==1||y==2||y==6){
        soma+=3;
        if (y==6)
          fdigit=1;
      }
      else if (y==4||y==5||y==9){
        soma+=4;
        if (y==4||y==9)
          fdigit=1;
      }
      else if (y==3||y==8||y==7){
        soma+=5;
        if (y==7)
          fdigit=1;
      }        
    } /* end of if */

    if (counter==1){
      if (y==1){
        if (fdigit==1)
          soma+=4;
        else
          soma+=3;
      }
      else if (y==2||y==3||y==8||y==9)
        soma+=6;
      else if (y==4||y==5||y==6)
        soma+=5;
      else if (y==7)
        soma+=7;        
    } /* end of if */

    if (counter==2){
      if (y==1||y==2||y==6)
        soma+=13;
      else if (y==4||y==5||y==9)
        soma+=14;
      else if (y==3||y==8||y==7)
        soma+=15;        
    } /* end of if */

  x = x / 10;
  counter++;  
  } /* end of while */
} /* end of for */  

printf("soma -> %dn",soma);
return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *