(EDIT: here is the follow up qusetion)
Using this program to test for the smallest number where its permutations or itself is divisible by 10 or less numbers is twice as slow as the fastest program I found doing this (I don't have the source code). How can this program be twice as slow, what optimizations can I do without messing with the compiler flags?
#include <stdio.h>
#include <string.h>
#define MAX 1000000
int main() {
int N,p[10],n[100];
int mask[MAX];
register int i, j, k;
scanf("%d", &N);
for(i=0;i<N;i++) scanf("%d", &n[i]);
memset(mask,0,sizeof(mask));
i = MAX+1;
while(--i) {
k=i;
p[0]=0;
p[1]=0;
p[2]=0;
p[3]=0;
p[4]=0;
p[5]=0;
p[6]=0;
p[7]=0;
p[8]=0;
p[9]=0;
while (k>0) {p[k%10]++; k/=10;}
for(j=1;j<10;j++) if(p[j]>0) {k=j; p[j]--; break;}
for(j=0;j<10;j++) while (p[j]>0) {k=10*k+j; p[j]--;}
for(j=0;j<N;j++) if(i%n[j]==0) mask[k]|=(1<<j);
}
for(i=1;i<MAX;i++) if(mask[i]==(1<<N)-1) break;
fprintf(stdout, "%d\n", i);
}
This program uses bitmasks to test all numbers between 1 and MAX for divisibility with the given numbers and then prints out the smallest number whose permutations or itself is divisible by all given numbers. It is not fast enough!
Example input
7
164 278 293 382 483 598 23
This will test all numbers and check which ones are divisible by the given numbers and the output should be 102246
.
It is compiled using the GCC compiler with the following flags:
-g -O2 -std=gnu99 -static -lm
Test the code here.
#include <string.h>
Always compile with all warnings enabled. (for gcc, at a minimum use:-Wall -Wextra -pedantic
) then fix those warnings. \$\endgroup\$#include <math.h>
\$\endgroup\$register
modifier has only one effect, namely that the address of the associated variable cannot be acquired. \$\endgroup\$scanf("%d", &N);
has a couple of problems. 1) always check the returned value from scanf() to assure the operation was successful. 2) the value input into 'N' is not checked to assure it is in the range of 1,,,99. 3) the user of this program will be staring at a blinking cursor and have no indication of what to do next. (I.E. prompt the user and check the results for validity \$\endgroup\$