Solution to Problem 32 on ProjectEuler


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

The problem:

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.

The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.

Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.

HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.

My Solution


#include <stdio.h>

int findLen(int n){
  int i=0;
  while (n>0){
    i++;
    n/=10;
  }
  return i;
}

int hasDigit (int n,int digits[]){
  int i;

  for (i=0;i<9;i++)
    if (digits[i]==n)
      return 1;
  return 0;
}

int main(){
  int digits[9];
  int i,j,z,product;
  int a,b,c,k;
  int leni,lenj,lenp,digit,erro;
  int multiplicand,multiplier,productcopy;

  for (i=1;i<500;i++){
    for (j=1;j<2000;j++){
      for (k=0;k<9;k++)
        digits[k]=0;      
      erro=0;
      multiplier=j;
      multiplicand = i;
      z = 0;
      product = i * j;
      productcopy = product;
      leni = findLen(i);
      lenj = findLen(j);
      lenp = findLen(product);
      if (leni+lenj+lenp!=9)
        continue;
      for (a=0;a<leni;a++){
        digit = multiplicand%10;        
        if (hasDigit(digit,digits))
          erro=1;
        digits[z++]=digit;
        multiplicand/=10;        
      }
      
      for (b=0;b<lenj;b++){
        digit = multiplier%10;
        if (hasDigit(digit,digits))
          erro=1;
        digits[z++]=digit;
        multiplier/=10;        
      }
      
      for (c=0;c<lenp;c++){
        digit = productcopy%10;        
        if (hasDigit(digit,digits))
          erro=1;
        digits[z++]=digit;
        productcopy/=10;        
      }      
      if (erro)
        continue;
      else  
        printf("%d\n",product);      
    }
  }  

return 0;
}

4 thoughts on “Solution to Problem 32 on ProjectEuler

Leave a Reply

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