1. 程式人生 > >Project Euler Problem 43

Project Euler Problem 43

Problem 43 : Sub-string divisibility

The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property.

Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:

d2d3d4=406 is divisible by 2
d3d4d5=063 is divisible by 3
d4d5d6=635 is divisible by 5
d5d6d7=357 is divisible by 7
d6d7d8=572 is divisible by 11
d7d8d9=728 is divisible by 13
d8d9d10=289 is divisible by 17

Find the sum of all 0 to 9 pandigital numbers with this property.

#include <iostream>
#include <string> #include <sstream> #include <algorithm> // next_permutation() #include <cassert> // assert() #include <ctime> // clock() using namespace std; // #define UNIT_TEST struct _SubStrDivisibility { int pos; // sub-string start position int d; // divisor
} subStrDiv[] = {{8, 17}, {7, 13}, {6, 11}, {5, 7}, {4, 5}, {3, 3}, {2, 2}}; class PE0043 { private: static const int m_maxSubStrLength = 3; static const int max_digits = 10; string m_digitsString; long long getLongLongInt() const; bool checkNumberOfSubString(int starting, int divisor); bool checkPandigitalNumber(); public: long long getSumOfProperPandigitalNumbers(); }; bool PE0043::checkPandigitalNumber() { for(int i=0; i<sizeof(subStrDiv)/sizeof(_SubStrDivisibility); i++) { if (false == checkNumberOfSubString(subStrDiv[i].pos,subStrDiv[i].d)) { return false; } } return true; } bool PE0043::checkNumberOfSubString(int startPos, int divisor) { int digit; int subStringNumber = 0; for (int i=startPos; i<startPos+m_maxSubStrLength; i++) { digit = m_digitsString[i-1] - '0'; subStringNumber = 10*subStringNumber + digit; } if (0 == subStringNumber % divisor) { return true; } return false; } long long PE0043::getLongLongInt() const { long long n; stringstream os; os << m_digitsString; os >> n; return n; } long long PE0043::getSumOfProperPandigitalNumbers() { m_digitsString = "1406357289"; assert(true == checkPandigitalNumber()); long long factorial_n = max_digits; for( long long n=factorial_n-1; n>=1; n-- ) { factorial_n *= n; } long long int sum = 0; for(int i=1; i<=factorial_n; i++) { if (true == checkPandigitalNumber()) { #ifdef UNIT_TEST cout << m_digitsString << endl; #endif sum += getLongLongInt(); } next_permutation(m_digitsString.begin(), m_digitsString.end()); } return sum; } int main() { clock_t start = clock(); PE0043 pe0043; cout << "The sum of all 0 to 9 pandigital numbers with this property is "; cout << pe0043.getSumOfProperPandigitalNumbers() << endl; clock_t finish = clock(); double duration = (double)(finish - start) / CLOCKS_PER_SEC; cout << "C/C++ application running time: " << duration << " seconds" << endl; return 0; }