帅气的(BTp堡)来发帖子啦
13. 平方和
题目ID:7726 拓展题100分
最新提交:
Time Limit Exceeded30 分
历史最高:
Time Limit Exceeded30 分
时间限制: 1000ms
空间限制: 262144kB
题目描述
求12+22+…+n2的值
输入格式:
一行一个整数n
输出格式:
按题目描述输出
样例输入1:
3
样例输出1:
14
约定:
n<=1e18
本人代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
string ans, s = "0";
int x[N], y[N], c[N], n;
string jia(string a, string b) {
ans = "";
memset(x, 0, sizeof(x));
memset(y, 0, sizeof(y));
memset(c, 0, sizeof(c));
int lena = a.size(), lenb = b.size(), lenc = max(lena, lenb) + 1;
for (int i = 0; i < lena; i++) {
x[lena - i] = a[i] - '0';
}
for (int i = 0; i < lenb; i++) {
y[lenb - i] = b[i] - '0';
}
for (int i = 1; i <= lenc; i++) {
c[i] += x[i] + y[i], c[i + 1] += c[i] / 10, c[i] %= 10;
}
while (lenc > 1 && c[lenc] == 0) {
lenc--;
}
for (int i = lenc; i > 0; i--) {
ans += c[i] + '0';
}
return ans;
}
string cheng(string a, string b) {
ans = "";
memset(x, 0, sizeof(x));
memset(y, 0, sizeof(y));
memset(c, 0, sizeof(c));
int lena = a.size(), lenb = b.size();
int lenc = lena + lenb;
for (int i = 0; i < lena; i++) x[lena - i] = a[i] - '0';
for (int i = 0; i < lenb; i++) y[lenb - i] = b[i] - '0';
for (int i = 1; i <= lena; i++)
for (int j = 1; j <= lenb; j++) {
c[i + j - 1] += x[i] * y[j];
c[i + j] += c[i + j - 1] / 10;
c[i + j - 1] %= 10;
}
while (lenc > 1 && c[lenc] == 0) lenc--;
for (int i = lenc; i > 0; i--) ans += c[i] + '0';
return ans;
}
void init() {
cin >> n;
}
void js() {
for (int i = 1; i <= n; i++) {
s = jia(s, cheng(to_string(i), to_string(i)));
}
}
void print() {
cout << s;
}
int main() {
init();
js();
print();
return 0;
}
好心人帮我看一看吧!
给你磕一个头: