对于给定的正整数n,求1+2+3+4+……+n采用逐个累加与n(n+1)/2(高斯法)两种解法。对于相同的n,给出求和结果和求解时间,用相关数据(n=9999 9999)进行测试。)

。。。。。。。。。强。。。。。。。。。。。
。。。。。。。。。强。。。。。。。。。。。
。。。。。。。。。强。。。。。。。。。。。


#include <stdio.h>
#include <time.h>             //clock_t, clock, CLOCKS_PER_SEC
#include <math.h>

//------方法1-----------------------------------------------
long add1(long n)            //方法1:求1+2+...+n
{
    long i,sum=0;
    for (i=1;i<=n;i++)
        sum+=i;
    return sum;
}

void AddTime1(long n)        //采用方法1的耗时统计
{
    clock_t t;
    long sum;
    t=clock();
    sum=add1(n);
    t=clock()-t;
    printf("方法1:\n");
    printf("  结果:1~%d之和:%ld\n",n,sum);
    printf("  用时:%lf秒\n" ,((float)t)/CLOCKS_PER_SEC);
}

//------方法2-----------------------------------------------
long add2(long n)            //方法2:求1+2+...+n
{
    return n*(n+1)/2;
}
void AddTime2(long n)        //采用方法2的耗时统计
{
    clock_t t;
    long sum;
    t=clock();
    sum=add2(n);
    t=clock()-t;
    printf("方法2:\n");
    printf("  结果:1~%d之和:%ld\n",n,sum);
    printf("  用时:%lf秒\n" ,((float)t)/CLOCKS_PER_SEC);
}
//------------------------------------------------------------
int main()
{
    int n;
    printf("n(大于1000000):");
    scanf("%d",&n);
    if (n<1000000) return 0;
    AddTime1(n);
    AddTime2(n);
    return 1;
}

img

有帮助望采纳

#include <stdio.h>
#include <math.h>
#include <time.h>

#define n 99999999L
int main(int argc, char const *argv[])
{
    clock_t start1, start2, start3, start4;

    long long int sum1 = 0, sum2 = 0;
    start1 = clock();
    for (int i = 0; i <= n; i++)
    {
        sum1 += i;
    }
    start2 = clock();
    start3 = clock();
    sum2 = (long long int)((1 + n) / 2) * (long long int)n;
    start4 = clock();
    printf("%lli,%lli\n", sum1, sum2);
    printf("%lli,%lli\n", start2 - start1, start4 - start3);
    printf("%lli", start4);

    return 0;
}

img