//------------------------------------------------------------------------- // enigma1350.c (c) 2005 by Charles Petzold (www.charlespetzold.com) // // "All But One" from New Scientist, 23 July 2005, page 47. // // Four unique positive digits. All the 4-digit numbers formed by all 24 // combinations of the digits are summed, then one is subtracted. The // result is 122??0. What is the subtracted number? //------------------------------------------------------------------------- #include int main (void) { int i1, i2, i3, i4; // Go through all the combinations of four positive unique // digits. The arrangement of the loops implies that // i1 < i2 < i3 < i4, but that doesn't matter because // we're looking at all combinations of these digits. for (i1 = 1; i1 < 7; i1++) for (i2 = i1 + 1; i2 < 8; i2++) for (i3 = i2 + 1; i3 < 9; i3++) for (i4 = i3 + 1; i4 < 10; i4++) { // The sum of all the four-digit numbers formed // by all 24 combinations of these digits // can be easily calculated. Consider that the // least significant digit of the sum contains // six i1's plus six i2's plus six i3's plus // six i4's. The other columns are also the // sums of these digits, so: int sum = 6666 * (i1 + i2 + i3 + i4); // An array containing the four digits: int array[] = { i1, i2, i3, i4 }; // These four integers will index that array: int pos1, pos2, pos3, pos4; // Loop through the indices. for (pos1 = 0; pos1 < 4; pos1++) for (pos2 = 0; pos2 < 4; pos2++) for (pos3 = 0; pos3 < 4; pos3++) for (pos4 = 0; pos4 < 4; pos4++) { int excnum, x; // I hate this code, but... if (pos1 == pos2 || pos1 == pos3 || pos1 == pos4 || pos2 == pos3 || pos2 == pos4 || pos3 == pos4) continue; // Here's the excluded number. Subtract it from the sum. excnum = 1000 * array[pos4] + 100 * array[pos3] + 10 * array[pos2] + array[pos1]; x = sum - excnum; // Now see if it fits the pattern 122??0 if (x / 1000 == 122 && x % 10 == 0) printf("Sum = %i\nSum - Excluded = %i\nExcluded = %i\n", sum, x, excnum); } } return 0; }