Self powers | Project Euler | Problem #48
URL to the problem page: https://projecteuler.net/problem=48
The series, 1¹ + 2² + 3³ + ... + 10¹⁰ = 10405071317.
Find the last ten digits of the series, 1¹ + 2² + 3³ + ... + 1000¹⁰⁰⁰.
The series, 1¹ + 2² + 3³ + ... + 10¹⁰ = 10405071317.
Find the last ten digits of the series, 1¹ + 2² + 3³ + ... + 1000¹⁰⁰⁰.
#include <iostream>
using namespace std;
int main()
{
const int k = 10;
int result[4][k], carry[4], sum[k] = { 0 }, number2[4] = { 0, 0, 0, 0 }, i, j, a, b, tmp, carry_4, number[k];
for (a = 0; a < 1000; a++) {
for (j = 0; j < k; j++) {
number[j] = 0;
}
for (j = 3; j >= 0; j--) {
if (number2[j] == 9) {
number2[j] = 0;
}
else if (number2[j] < 9) {
number2[j]++;
break;
}
}
number[k - 1] = number2[3];
number[k - 2] = number2[2];
number[k - 3] = number2[1];
number[k - 4] = number2[0];
for (j = 0; j < a; j++) {
for (i = 0; i < 4; i++) {
carry[i] = 0;
for (b = 0; b < k; b++) {
result[i][b] = 0;
}
}
for (i = k - 1; i >= 0; i--) {
result[3][i] = ((number[i] * number2[3]) + carry[0]) % 10;
carry[0] = ((number[i] * number2[3]) + carry[0]) / 10;
result[2][i] = ((number[i] * number2[2]) + carry[1]) % 10;
carry[1] = ((number[i] * number2[2]) + carry[1]) / 10;
result[1][i] = ((number[i] * number2[1]) + carry[2]) % 10;
carry[2] = ((number[i] * number2[1]) + carry[2]) / 10;
result[0][i] = ((number[i] * number2[0]) + carry[3]) % 10;
carry[3] = ((number[i] * number2[0]) + carry[3]) / 10;
}
number[k - 1] = result[3][k - 1];
number[k - 2] = (result[3][k - 2] + result[2][k - 1]) % 10;
carry_4 = (result[3][k - 2] + result[2][k - 1]) / 10;
number[k - 3] = (result[3][k - 3] + result[2][k - 2] + result[1][k - 1] + carry_4) % 10;
carry_4 = (result[3][k - 3] + result[2][k - 2] + result[1][k - 1] + carry_4) / 10;
number[k - 4] = (result[3][k - 4] + result[2][k - 3] + result[1][k - 2] + result[0][k - 1] + carry_4) % 10;
carry_4 = (result[3][k - 4] + result[2][k - 3] + result[1][k - 2] + result[0][k - 1] + carry_4) / 10;
for (i = k - 5; i >= 0; i--) {
number[i] = (result[3][i] + result[2][i + 1] + result[1][i + 2] + result[0][i + 3] + carry_4) % 10;
carry_4 = (result[3][i] + result[2][i + 1] + result[1][i + 2] + result[0][i + 3] + carry_4) / 10;
}
}
carry_4 = 0;
for (i = k - 1; i >= 0; i--) {
tmp = sum[i];
sum[i] = (sum[i] + number[i] + carry_4) % 10;
carry_4 = (tmp + number[i] + carry_4) / 10;
}
}
cout << "Last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000 is = ";
for (i = k - 10; i < k; i++) {
cout << sum[i];
}
return 0;
}
Comments
Post a Comment