I - the Sum of Cube

I - the Sum of Cube

Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Submit

Status
Description
A range is given, the begin and the end are both integers. You should sum the cube of all the integers in the range.

Input
The first line of the input is T(1 <= T <= 1000), which stands for the number of test cases you need to solve.
Each case of input is a pair of integer A,B(0 < A <= B <= 10000),representing the range[A,B].

Output
For each test case, print a line “Case #t: ”(without quotes, t means the index of the test case) at the beginning. Then output the answer – sum the cube of all the integers in the range.

Sample Input
2
1 3
2 5

Sample Output
Case #1: 36
Case #2: 224


  1. 题意:给你一个整数范围,求在此闭区间内所有整数的立方之和。
  2. 思路:打表出立方区间和数组,根据所给区间输出。
  3. 失误:整形溢出;虽然用了方法2 错了几次 但还是推荐用代码2的方法,一是公式的推导,二是数据类型的选择。
  4. 代码如下:
1.
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;

__int64 c[11111]={0},a[11111]={0};//__int64 :1.84*1e19,unsigned int :4.2*1e9
                               // 可以推出最大区间之和用__int64不会溢出,但是要注意乘法运算!!!不过此题没有涉及


int main()
{
    __int64 i,j,l,t,flag,m,n,s,cnt,k,L,R,ch;

    for(i=1;i<=10010;++i)
    {
         a[i]=i*i*i;
         c[i]=c[i-1]+a[i];
    }

    k=0;
    cin>>t;
    while(t--)
    {
        cin>>L>>R;
        cout<<"Case #"<<++k<<": "<<c[R]-c[L-1]<<endl;
    }


    return 0;
}

2.
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdio>
using namespace std;

double a[10010]; //全局变量不赋初值默认为0 ,此处用float就错 用double和__int64都可以过
                 // double占内存大,运算速度慢 但精度高
                 //float耗内存小 运算快 但精度不高 在赋初值:float n=5.0时就可能出错 
int main()      //此处应该是精度溢出 所以说:int常为范围溢出  float常为精度溢出 
{


     __int64 m,i,n,t,k,j,R,L;

     for(i=1;i<=10010;++i)    //也可以不用打表 直接用公式计算两个值 
     {
        a[i]=i*i*(i+1)*(i+1)/4;
     }

     k=0;
     cin>>t;
     while(t--)
     {
        cin>>L>>R;
        cout<<"Case #"<<++k<<": "; 
        printf("%.f\n",a[R]-a[L-1]);//注意格式的控制
     }
    return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值