Problem Description
You just need to calculate the sum of the formula: 1^2+3^2+5^2+……+ n ^2.
Input
In each case, there is an odd positive integer n.
Output
Print the sum. Make sure the sum will not exceed 2^31-1
Sample Input
3
Sample Output
10
n = eval(input('请输入一个数字:'))#输入一个整数
sum = 0#定义求和变量
for i in range(n+1):
if i%2==0:#如果是偶数那么就不管不记录
pass
else:#只记录奇数
#print(i,end=' ')
sum += i**2#主要算法
print('sum=',sum)
这是Python思路,你照着看下
代码如下,经过调试。输出的字符可以更改。
#include
#include
#include
#define max_sum 0x7fffffff
int main()
{
unsigned long int sum;
unsigned int n,i;
sum = 0 ;
printf("Input the odd positive integer : n=");
scanf("%d",&n);
if(n%2 == 0) {
printf("Input error!\n");
return 0;
}
for(i=1;i<=n;i=i+2){
sum = sum + i*i;
if(sum > max_sum) {
printf("Output sum is over 2^31-1 !\n");
return 0;
}
}
printf(" sum = %d \n",sum);
return 0;
}