问题描述
输入x,输出1+2+3+...+x
输入格式
输入包含一个整数x。
输出格式
输出答案。
样例输入
10
样例输出
55
数据规模和约定
1<=x<=10^2000
这道题因为输入的数是高精度,所以肯定要用等差数列求和公式
所以1+2+3+……+x=x(x-1)/2
那么这个要用乘法和除法,而乘法要用加法,除法要用减法所以加减乘除都要用
然后就可以运算了
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
int cmp(string a,string b){
if (a.size() != b.size()){
if (a.size() > b.size()) return 1;
else return -1;
} else {
if (a > b) return 1;
else if (a == b) return 0;
else return -1;
}
}
string add(string a,string b){
int n = max(a.size(),b.size()) + 1;
vector<int>ans(n,0);
int i = a.size() - 1,j = b.size() - 1,k = n - 1;
while (i >= 0 && j >= 0){
ans[k--] = (a[i--] - '0') + (b[j--] - '0');
}
while (j >= 0){
ans[k--] = (b[j--] - '0');
}
while (i >= 0){
ans[k--] = (a[i--] - '0');
}
string c = "";
for (int i = n - 1;i > 0;i--){
if (ans[i] >= 10){
ans[i] -= 10;
ans[i - 1]++;
}
c.insert(0,1,ans[i] + '0');
}
if (ans[0] > 0){
c.insert(0,1,ans[0] + '0');
}
return c;
}
string sub(string a,string b){
string c = "";
if (cmp(a,b) == 0) return "0";
if (cmp(a,b) == -1){
swap(a,b);
c.push_back('-');
}
int n = a.size();
vector<int>ans(n,0);
int i = a.size() - 1,j = b.size() - 1,k = n - 1;
int t = 0;
while (i >= 0) {
char nowb;
if (j >= 0) nowb = b[j];
else nowb = '0';
ans[k] = a[i] - nowb - t;
if (ans[k] < 0){
t = 1;
ans[k] += 10;
}
else t = 0;
k--,i--,j--;
}
bool flag = true;
for (int i = 0;i < n;i++){
if (flag && ans[i] == 0) continue;
flag = false;
c.push_back(ans[i] + '0');
}
return c;
}
string mul(string a,string b){
if (a == "0" || b == "0") return "0";
vector<int>ans;
int n = a.size(),m = b.size();
ans.resize(n + m,0);
for (int i = 0;i < n;i++){
for (int j = 0;j < m;j++){
ans[i + j + 1] += (a[i] - '0') * (b[j] - '0');
}
}
for (int i = n + m - 1;i > 0;i--){
if (ans[i] >= 10){
ans[i - 1] += (ans[i] / 10);
ans[i] %= 10;
}
}
string c = "";
bool flag = true;
for (int t = 0;t < n + m;t++){
if (flag && ans[t] == 0) continue;
flag = false;
c.push_back(ans[t] + '0');
}
return c;
}
vector<string>divide(string a,string b){
vector<string>ans(2,"0");
if (cmp(a,b) == -1){
ans[1] = a;
return ans;
}
else if (cmp(a,b) == 0){
ans[0] = "1";
return ans;
} else {
string res = "";
int m1 = a.size(),m2 = b.size();
string a1 = a.substr(0,m2 - 1);
for (int i = m2 - 1;i < m1;i++){
if (a1 == "0") a1 = "";
a1.push_back(a[i]);
int e = 0;
while (cmp(a1,b) >= 0){
e++;
a1 = sub(a1,b);
}
if (res.size() || e)
res.push_back(e + '0');
}
ans[0] = res;
ans[1] = a1;
return ans;
}
}
int main(){
string a,b,c = "1",d,f = "2";
vector<string>e(2,"");
cin >> a;
b = add(a,c);
d = mul(a,b);
e = divide(d,f);
cout << e[0];
return 0;
}