//---------------------------------------------------------------------- // enigma1362.c (c) 2005 by Charles Petzold // // "Eight-Fifths" by Richard England, New Scientist, 15 October 2005, page 54. // // Assume 5 Miles = 8 Kilometers. What the least integral number of // miles so rearranging the digits yields the the equivalent integral // kilometers? // // Let M be miles and K kilometers. The conversion formula is: // // M = (5 / 8) * K // // or: // // 8 * M = 5 * K // // If both M and K are integers, M obviously includes a factor of 5, // and K includes a factor of 8. Both M and K can be written as these // factors times a common integer A: // // M = 5 * A // K = 8 * A // // So, we're looking for an A such that M and K have the same digits // but mixed up. //---------------------------------------------------------------------- #include // This function uses an array 'arr[10]' to tally the numbers of each // digit that appears in the 'num' argument. // It conveniently initializes the array to zero as a preliminary. void TallyDigits(int num, int arr[]) { int i; for (i = 0; i < 10; i++) arr[i] = 0; do { ++arr[num % 10]; } while (num /= 10); } int main(void) { int M, K, A, i; int Mdigits[10], Kdigits[10]; // Loop through possible A values for (A = 1; ; A++) { // Calculate the miles and kilometers for that value of A M = 5 * A; K = 8 * A; // Tally the digits TallyDigits(M, Mdigits); TallyDigits(K, Kdigits); // Check if the two arrays are the same for (i = 0; i < 10; i++) { if (Mdigits[i] != Kdigits[i]) break; } // If so, print the result if (i == 10) { printf("%i Miles = %i Kilometers\n", M, K); return 0; } } }