错误解法:
#include <stdio.h>
int main()
{
int n;
while(scanf("%d", &n) != EOF)
{
int ans = n*(n+1)/2;
printf("%d\n", ans);
}
return 0;
}
原因:当n=65535时,n*(n+1)为65535*65536,而int的最大值为65535,会导致溢出
正确解法如下:
#include <stdio.h>
int main()
{
int n,ans;
while(scanf("%d", &n) != EOF)
{
if(n % 2 == 0)
{
ans = n / 2 * (n+1);
}
else
{
ans = (n+1) / 2 * n;
}
}
printf("%d\n", ans);
return 0;
}
解析:当n为偶数,先n/2 再乘上(n+1)就不会溢出;
当n为奇数,先(n+1)/2再乘上n就不会溢出;
循环枚举:
#include <stdio.h>
int main()
{
int n,ans;
while(scanf("%d", &n) != EOF)
{
ans = 0;
while(n--)
{
ans += n;
}
}
return 0;
}
使用范围更大的数据类型:
1.unsigned int:
#include <stdio.h>
int main()
{
unsigned int n;
while(scanf("%u", &n) != EOF)
{
unsigned int ans = n * (n + 1) / 2;
printf("%u\n", ans);
}
return 0;
}
解析:unsigned int 范围足够大,所以不用担心溢出
2.long long :
#include <stdio.h>
int main()
{
long long n;
while(scanf("%lld", &n) != EOF)
{
long long ans = n * (n + 1) / 2;
printf("%lld\n", ans);
}
return 0;
}
解析:long long 类型范围更大