// Problem 38 // 28 February 2003 // // Take the number 192 and multiply it by each of 1, 2, and 3: // // 192 1 = 192 // 192 2 = 384 // 192 3 = 576 // By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) // // The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). // // What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n 1? #include <iostream> #include <windows.h> #include <ctime> using namespace std; // 获取某数的位数 int GetDigitCount(int num) { int count = 0; while(num != 0) { count++; num /= 10; } return count; } // 查询num位是否存在(1<=num<=9),使用位记录,记录于digitRecoder中 // 如果存在了此位,返回false,否则返回true bool RecoderBit(int &digitRecoder, const int num) { if((digitRecoder & (1 << num)) == (1 << num)) //此位已存在 { return false; } digitRecoder |= (1 << num); //此位不存在,记录此位 return true; } // 检测num是否符合要求,如果符合,把拼接数放入pandigitalNum中 bool CheckConcatenatedProduct(const int num, int &pandigitalNum) { int digitRecoder = 0; //用位来记录 int product = 0; //记录乘积 pandigitalNum = 0; int currentDigit = 0; //当前进行判断的数字 static const int ALL_1_TO_9 = 0x3FE; //bit位为1111111110,表示1~9所有位都存在 for(int i = 1; i <= 9; i++) { product = i * num; for(int j = GetDigitCount(product); j > 0; j--) //在后面添加product位数个数的0,用于拼接新数 { pandigitalNum *= 10; } pandigitalNum += product; //拼接新数 while(product != 0) { currentDigit = product % 10; //获取最低位 if(!RecoderBit(digitRecoder, currentDigit)) //如果此位已存在,则跳过 { break; } product /= 10; } if(product != 0) //表明测试未通过 { return false; } if(digitRecoder == ALL_1_TO_9) //表示测试通过 { return true; } } return false; } void F1() { cout << "void F1()" << endl; LARGE_INTEGER timeStart, timeEnd, freq; QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&timeStart); const int MAX_NUM = 9876; int pandigitalNum = 0; //拼接数 int maxPandigitalNum = 0; //最大的拼接数 int maxPandigitalNumFromNum = 0; //最大的拼接数对应的生成数 for(int i = 0; i <= MAX_NUM; i++) { if(CheckConcatenatedProduct(i, pandigitalNum)) { if(pandigitalNum > maxPandigitalNum) { maxPandigitalNum = pandigitalNum; maxPandigitalNumFromNum = i; } } } cout << "最大的拼接数为" << maxPandigitalNumFromNum << "产生的" << maxPandigitalNum << endl; QueryPerformanceCounter(&timeEnd); cout << "Total Milliseconds is " << (double)(timeEnd.QuadPart - timeStart.QuadPart) * 1000 / freq.QuadPart << endl; time_t currentTime = time(NULL); char timeStr[30]; ctime_s(timeStr, 30, ¤tTime); cout << endl << "By GodMoon" << endl << timeStr; } //主函数 int main() { F1(); return 0; } /* void F1() 最大的拼接数为9327产生的932718654 Total Milliseconds is 17.9625 By GodMoon Sat Nov 05 15:12:43 2011 */