Solution to Problem 29 on Project Euler


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

The problem:

Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:

22=4, 23=8, 24=16, 25=32
32=9, 33=27, 34=81, 35=243
42=16, 43=64, 44=256, 45=1024
52=25, 53=125, 54=625, 55=3125

If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:

4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125

How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?

My Solution


#include <stdio.h>
#include <string.h>

#define CHARACTERS 220
#define NUMBERS 10000

void calcNum (int a,int b,char v[CHARACTERS]){
  int i,j,z;
  int vai=0;
  int multi;

  for (i=0;i<CHARACTERS;i++)
    v[i]='*';
  if (a<10)
    v[0]=a;
  else if (a<100){
    v[0]=a%10;
    v[1]=a/10;
  }
  else{
    v[0]=0;
    v[1]=0;
    v[2]=1;
  }

  for (i=0;i<b-1;i++){
    for (j=0;j<CHARACTERS;j++){
      if (v[j]=='*'&&vai==0)
        break;
      else if (v[j]=='*'){
        if (vai<10){
          v[j]=vai;
          vai=0;
        }
        else{
          v[j]=vai%10;
          vai=vai/10;
        }  
      }      
      else{  
        multi = v[j]*a + vai;
        vai = 0 ;
        if (multi>9){
          v[j]=multi%10;
          vai =multi/10;          
        }
        else
          v[j]=multi;
        
      }
    }
  }

return;
}

int main(){  
  char vetor[NUMBERS][CHARACTERS];
  char aux[CHARACTERS];
  int a,b,i,k,m;
  int z = 0;
  int counter,igual;  
  
  for (i=0;i<NUMBERS;i++)  
    strcpy(vetor[i],"*");

  for (a=2;a<101;a++){
    for(b=2;b<101;b++){      
      calcNum(a,b,aux);                    
      igual=0;      
      for (i=0;i<z;i++){/*checar se tem igual*/        
        counter=0;      
        for(k=0;k<CHARACTERS;k++){                    
          if (vetor[i][k]==aux[k]){
            counter++;            
          }                              
        }                        
        if (counter==CHARACTERS){              
          igual=1;          
        }      
      }/*fim da checagem*/            
      if (igual){  
        //for (m=0;m<CHARACTERS;m++)
        //  printf("%d,",aux[m]);
        //printf("\n");    
        continue;
      }
      else {            
        for (m=0;m<CHARACTERS;m++)
          vetor[z][m]=aux[m];        
        z++;
      }
    }
  }
  printf("z=%d\n",z);
  
return 0;
}

Leave a Reply

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