题解
2025-05-14 19:45:10
发布于:浙江
10阅读
0回复
0点赞
方法一:
思路:就是一个等差数列,直接用for循环遍历相加在输出即可:
#include <iostream>
using namespace std;
int main(){
int a;
cin >> a;
int ans=0;
for(int i=1;i<=a;i++)
ans+=i;
cout << ans;
return 0;
}
时间复杂度:
方法二:
上面提到过,这是一个等差数列。根据等差数列的特性,(这里把长度看为a,序列最后一项为n),即为详细解释就是序列第一项加序列最后一项的和乘序列长度除以二。而这里,所以本题就是:
#include <iostream>
using namespace std;
int main(){
int a;
cin >> a;
cout << (1+a)*a/2;
return 0;
}
时间复杂度:
这里空空如也
有帮助,赞一个