Project Euler Problem 56 (C++和Python)
阿新 • • 發佈:2018-12-26
Problem 56 : Powerful digit sum
A googol (10100) is a massive number: one followed by one-hundred zeros; 100100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum?
C++程式碼
#include <iostream>
using namespace std;
//#define UNIT_TEST
class PE0056
{
private:
static const int max_digits = 200;
int m_digitsArray[max_digits];
void adjustMyDigitArray(int myDigitArray[]);
int getPowerDigitsSum(int a, int b);
public:
int getMaxDigitsSum ();
};
void PE0056::adjustMyDigitArray(int myDigitArray[])
{
for(int j=0; j<max_digits-1; j++)
{
myDigitArray[j+1] += myDigitArray[j]/10;
myDigitArray[j] %= 10;
}
}
int PE0056::getPowerDigitsSum(int a, int b)
{
for(int j=0; j<max_digits; j++)
{
m_digitsArray[ j] = 0;
}
m_digitsArray[0] = 1;
for(int i=1; i<=b; i++)
{
for(int j=0; j<max_digits; j++)
{
m_digitsArray[j] *= a; // a^b
}
adjustMyDigitArray(m_digitsArray);
}
int digits_sum = 0;
for(int j=0; j<max_digits; j++)
{
digits_sum += m_digitsArray[j];
}
return digits_sum;
}
int PE0056::getMaxDigitsSum()
{
int digits_sum_max = 0;
int a_max = 0, b_max = 0;
int digits_sum = 0;
for (int a=2; a<100; a++)
{
for(int b=2; b<100; b++)
{
digits_sum = getPowerDigitsSum(a, b);
if (digits_sum > digits_sum_max)
{
digits_sum_max = digits_sum;
a_max = a;
b_max = b;
}
}
}
#ifdef UNIT_TEST
cout << "While a = " << a_max << " and b = " << b_max << ", ";
#endif
return digits_sum_max;
}
int main()
{
PE0056 pe0056;
cout << "the maximum digits sum is " << pe0056.getMaxDigitsSum();
cout << "." << endl;
return 0;
}
Python 程式碼
def getPowerDigitsSum(a, b):
p = 1
for i in range(b):
p *= a
digits_list = [ int(s) for s in list(str(p)) ]
return sum(digits_list)
def getPowerDigitsSumNew(a, b):
return sum(map(int, str(a**b)))
def getMaxDigitsSum():
digits_sum_max, a_max, b_max, digits_sum = 0, 0, 0, 0
for a in range(50, 100):
for b in range(50, 100):
digits_sum = getPowerDigitsSumNew(a, b)
if digits_sum > digits_sum_max:
digits_sum_max = digits_sum
a_max, b_max = a, b
print("Where a = ", a_max, "and b = ", b_max, ", ")
return digits_sum_max
def getMaxDigitsSumNew():
digits_sum_max = max((getPowerDigitsSum(a, b)) \
for a in range(50, 100) \
for b in range(50, 100))
return digits_sum_max
def main():
assert 1 == getPowerDigitsSum(10, 100)
assert 1 == getPowerDigitsSumNew(100, 100)
print("The maxium digits sum is", getMaxDigitsSumNew(), ".")
if __name__ == '__main__':
main()