zoukankan      html  css  js  c++  java
  • hdu 1001

    Problem Description

    Hey, welcome to HDOJ(Hangzhou Dianzi University Online Judge).
    In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + ... + n.

    Input

    The input will consist of a series of integers n, one integer per line.

    Output

    For each case, output SUM(n) in one line, followed by a blank line. You may assume the result will be in the range of 32-bit signed integer.

    Sample Input

    1 100

    Sample Output

    1 5050

    我的答案:

    #include <stdio.h>
    int main()
    {
       int i,n,sum;
       while(scanf("%d",&n)==1)
       {
          sum=0;
          for(i=1;i<=n;i++)
          sum+=i;
          printf("%d
    
    ",sum);
       }
       return 0;
    }

    或者

    #include <stdio.h>
    int main()
    {
       int i,n,sum;
       while(scanf("%d",&n)!=EOF)
       {
          sum=0;
          for(i=1;i<=n;i++)
          sum+=i;
          printf("%d
    
    ",sum);
       }
       return 0;
    }

    但是在网上找了一下,发现别人说这种暴力加法有时候很有可能超过内存限制,所以提高C程序运行效率的方式就是能用数学公式就尽量用。

    但是只是把加法换成公式这么简单吗?

    sum=n*(n+1)/2;

    提交WA,为什么呢?

    原因就在于题目上说n和sum是32位整形数据,但是n*(n+1)很有可能就爆了。所以得再加以修改。

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int n,sum;
        while(scanf("%d",&n)!=EOF)
        {
            if(n%2)
                sum=(n+1)/2*n;
            else
                sum=n/2*(n+1);
            printf("%d
    
    ",sum);
        }
        return 0;
    }

    另外有一个小坑follow a blank line。所以我们得用两个换行符。。。

  • 相关阅读:
    移动端兼容
    三点优化
    面向对象(一)
    BootCDN和npm
    分页逻辑
    多物体运动框架
    兼容样式
    省略
    行内元素在水平和垂直排列的时候会有间距
    [Swift]LeetCode1053.交换一次的先前排列 | Previous Permutation With One Swap
  • 原文地址:https://www.cnblogs.com/kugwzk/p/5046087.html
Copyright © 2011-2022 走看看