HDOJ 1001Sum Problem求和问题

版权声明:本文为博主原创文章,未经博主允许不得转载。http://blog.csdn.net/leytton https://blog.csdn.net/Leytton/article/details/79444157

0x00 前言

这道题也是很简单,不过一开始想当然地,用公式s=(1+n)*n/2一套带走,结果就踩了两个坑。
在线编程调试 http://www.dooccn.com/c/
Sum Problem原题 http://acm.hdu.edu.cn/showproblem.php?pid=1001

0x01 题目

Sum Problem
这道题要求输入整数n,输出1+2+3+...+n的结果。

0x02 错误写法

#include<stdio.h>
int main(){
    for(int n;~scanf("%d",&n);printf("%d\n",(1+n)*n/2));
    return 0;
}

有两个错误:
1、注意输出要求多了个空行
2、数据溢出
使用(1+n)*n/2会导致测试集数据溢出,改成(1+n)*(n/2),如果n为奇数,会漏掉中间项n/2+1,加上即可

0x03 修正版本

#include<stdio.h>
int main(){
    for(int n;~scanf("%d",&n);printf("%d\n\n",n%2==0?(1+n)*(n/2):(1+n)*(n/2)+n/2+1));
    return 0;
}

0x04 高效版

#include<stdio.h>
int main(){
    for(int n,t,k;~scanf("%d",&n);t=n>>1,k=(1+n)*t,printf("%d\n\n",n%2==0?k:k+t+1));
    return 0;
}

1、用n>>1代替n/2能提高程序执行效率
2、重复计算结果保存在变量t、k

【转载请注明出处: http://blog.csdn.net/leytton/article/details/79444157
PS:如果本文对您有帮助,请点个赞让我知道哦~微笑

猜你喜欢

转载自blog.csdn.net/Leytton/article/details/79444157