125 lines
1.7 KiB
C
125 lines
1.7 KiB
C
#include<stdio.h>
|
|
#include<stdlib.h>
|
|
|
|
#define MAX_NUM 9999
|
|
|
|
typedef struct Node {
|
|
int data;
|
|
struct Node* next;
|
|
} Node;
|
|
|
|
|
|
Node* create(int data, Node* node)
|
|
{
|
|
Node* new = (Node*)malloc(sizeof(Node));
|
|
if (new == NULL) {
|
|
printf("Error allocating memory\n");
|
|
exit(1);
|
|
}
|
|
|
|
new->data = data;
|
|
new->next = node;
|
|
return new;
|
|
}
|
|
|
|
|
|
Node* prepend(Node* head, int data)
|
|
{
|
|
return create(data, head);
|
|
}
|
|
|
|
|
|
int contains(Node* head, int data)
|
|
{
|
|
Node* cursor = head;
|
|
|
|
while (cursor != NULL) {
|
|
if (cursor->data == data)
|
|
return 1;
|
|
cursor = cursor->next;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
|
|
int sum(Node* head)
|
|
{
|
|
int total = 0;
|
|
Node* cursor = head;
|
|
|
|
while (cursor != NULL) {
|
|
total += cursor->data;
|
|
cursor = cursor->next;
|
|
}
|
|
|
|
return total;
|
|
}
|
|
|
|
|
|
int countDigits(long num)
|
|
{
|
|
int count = 0;
|
|
|
|
while (num != 0) {
|
|
count++;
|
|
num /= 10;
|
|
}
|
|
|
|
return count;
|
|
}
|
|
|
|
|
|
int isNineDigits(int i, int j)
|
|
{
|
|
return 9 == countDigits(i) + countDigits(j) + countDigits(i*j);
|
|
}
|
|
|
|
|
|
int isNinePandigital(int i, int j)
|
|
{
|
|
int rem;
|
|
int digits = 0;
|
|
int prod = i*j;
|
|
|
|
if (!(isNineDigits(i, j)))
|
|
return 0;
|
|
|
|
while (i>0) {
|
|
rem = i % 10;
|
|
digits ^= 1 << rem;
|
|
i /= 10;
|
|
}
|
|
|
|
while (j>0) {
|
|
rem = j % 10;
|
|
digits ^= 1 << rem;
|
|
j /= 10;
|
|
}
|
|
|
|
while (prod>0) {
|
|
rem = prod % 10;
|
|
digits ^= 1 << rem;
|
|
prod /= 10;
|
|
}
|
|
|
|
return digits == 1022; /* 1022 == 1111111110 in binary */
|
|
}
|
|
|
|
|
|
int main(int argc, char** argv)
|
|
{
|
|
int i, j;
|
|
int sumProds;
|
|
Node* pandigitals = NULL;
|
|
|
|
for (i=1; i<MAX_NUM; i++)
|
|
for (j=1; j<MAX_NUM; j++)
|
|
if (isNinePandigital(i, j) && !contains(pandigitals, i*j))
|
|
pandigitals = prepend(pandigitals, i*j);
|
|
|
|
sumProds = sum(pandigitals);
|
|
printf("The sum of the nine pandigital products is %d\n", sumProds);
|
|
return 0;
|
|
}
|