Problem 48 : Self powers
The series, 11 + 22+ 33 + … + 1010 = 10405071317.
Find the last ten digits of the series, 11 + 22 + 33 + … + 10001000.
C++ source code
#include <iostream>
#include <vector>
#include <iterator>
#include <cmath>
#include <cassert>
using namespace std;
class PE0048
{
private:
static const int max_last_digits = 10;
int m_lastDigitsArray[max_last_digits+1];
void getSelfPower(int n);
void adjustDigitsArray(int digitsArray[]);
public:
vector<int> getSumOfSelfPowers(int n);
void printLast10digits(int n, vector<int>& int_vec);
};
void PE0048::adjustDigitsArray(int digitsArray[])
{
for(int j=0; j<max_last_digits; j++)
{
digitsArray[j+1] += digitsArray[j]/10;
digitsArray[j] %= 10;
}
}
void PE0048::getSelfPower(int n)
{
for(int j=0; j<max_last_digits; j++)
{
m_lastDigitsArray[j] = 0;
}
m_lastDigitsArray[0] = 1;
for(int i=1; i<=n; i++)
{
for(int j=0; j<max_last_digits; j++)
{
m_lastDigitsArray[j] *= n;
}
adjustDigitsArray(m_lastDigitsArray);
}
}
vector<int> PE0048::getSumOfSelfPowers(int n)
{
int sumDigitArray[max_last_digits+1];
vector<int> resultArray(max_last_digits);
for(int j=0; j<max_last_digits; j++)
{
sumDigitArray[j] = 0;
}
for(int i=1; i<=n; i++)
{
getSelfPower(i);
for(int j=0; j<max_last_digits; j++)
{
sumDigitArray[j] += m_lastDigitsArray[j];
}
adjustDigitsArray(sumDigitArray);
}
for(int i=0; i<max_last_digits; i++)
{
resultArray[i] = sumDigitArray[9-i]; // the last ten digits
}
return resultArray;
}
void PE0048::printLast10digits(int n, vector<int>& int_vec)
{
cout << "The last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + ";
cout << n << "^" << n << ", are ";
copy(int_vec.begin(), int_vec.begin()+max_last_digits, ostream_iterator<int>(cout));
cout << endl;
}
int main()
{
PE0048 pe0048;
int seriesLastDigits[] = {0, 4, 0, 5, 0, 7, 1, 3, 1,7};
vector<int> seriesLastDigitsArray;
vector<int> resultLastDigitsArray;
seriesLastDigitsArray.assign(seriesLastDigits, seriesLastDigits+10);
resultLastDigitsArray = pe0048.getSumOfSelfPowers(10);
assert (seriesLastDigitsArray == resultLastDigitsArray);
resultLastDigitsArray = pe0048.getSumOfSelfPowers(1000);
pe0048.printLast10digits(1000, resultLastDigitsArray);
return 0;
Python source code
def getSelfPower(n):
"""
calculate self power of n
"""
p = 1
for i in range(n):
p *= n
return p
def getLastTenDigitsOfSumOfSelfPowers(n):
"""
calculate sum of self powers from 1 to n and return last ten digits
"""
sumOfSelfPowers = 0
for i in range(1, n+1):
sumOfSelfPowers += getSelfPower(i)
return str(sumOfSelfPowers)[-10:]
def main():
s0 = '10405071317'
assert getLastTenDigitsOfSumOfSelfPowers(10) == s0[-10:]
print("The last ten digits of the series (1^1 + 2^2 + 3^3"\
"+ ... + 1000^1000) are",getLastTenDigitsOfSumOfSelfPowers(1000))
if __name__ == '__main__':
main()