修改了之前一个类似问题的程序。关键是取值范围,然后把结果排序,和“0123456789”对比即可。
#include #include #include #include /* Is Duplication Composition -- abcd e fghij should be unique. */int isdupcom(const size_t abcd, const size_t e, const size_t fghij);/* compare function for qsort */int compare(const void * a, const void * b);int main(int argc, char** argv) { size_t abcd_min, abcd_max, e_min, e_max, fghij_max; size_t abcd, e, fghij, count; clock_t t; abcd_min = 1023; /* 4 digit lower boundary */ abcd_max = 9876; /* 4 digit upper boundary */ fghij_max = 98765; /* 5 digit upper boundary */ e_min = 1; /* 1 digit lower boundary */ e_max = 9; /* 1 digit upper boundary */ count = 0; /* counter, number of match found. */ t = clock(); /* timer starts */ for (e = e_min; e <= e_max; e++) { abcd = abcd_min; do { fghij = e * abcd; if ( !isdupcom(abcd, e, fghij) ) { printf(" %d * %d = %d\n", abcd, e, fghij); count ++; } abcd ++; } while ((fghij < fghij_max) && (abcd < abcd_max)); } t= clock() - t; /* timer ends. */ printf("Total found: %d\n", count); printf("Time elapsed: %d clicks (%g seconds).\n", t, ((double)t)/CLOCKS_PER_SEC); return 0;}int isdupcom(const size_t abcd, const size_t e, const size_t fghij){ char buffer[10]; snprintf(buffer, 10, "%4d%1d%5d", abcd, e, fghij); /* 4d-1d-5d is a MUST */ qsort(buffer, sizeof(buffer)/sizeof(buffer[0]), sizeof(char), compare); return strncmp(buffer, "0123456789", 10); }int compare(const void * a, const void * b){ return ( *(char*)a - *(char*)b ); }运行结果:
5694 * 3 = 17082 6819 * 3 = 20457 6918 * 3 = 20754 8169 * 3 = 24507 9168 * 3 = 27504 3907 * 4 = 15628 7039 * 4 = 28156 9127 * 4 = 36508 5817 * 6 = 34902 3094 * 7 = 21658 4093 * 7 = 28651 9304 * 7 = 65128 9403 * 7 = 65821Total found: 13Time elapsed: 98 clicks (0.098 seconds).
取消
评论