#include<iostream>
using namespace std;
int oddSum(int n) {
return n * n * (2 * n * n - 1);
}
int evenSum(int n) {
return 2 * 2 * n * (n + 1) * (2*n + 1) / 6;
}
int main() {
int N, m, n;
cin >> N;
while (N--) {
cin >> m >> n;
if (m > n) swap(m, n);
// sum(x^2) | m n
// 1^2 + ... + n^2 = n*(n+1)*(2n+1)/6
// (2*1)^2 + ... + (2*n)^2 = 4 * ( 1^2 + ... + n^2) = 4 * n*(n+1)*(2n+1)/6
cout << evenSum(n) - evenSum(m) << endl;
// 奇数sum(x^3) | m n
// (2*1-1)^3 + ... + (2*n-1)^3 = n^2 * (2*n^2 -1)
cout << oddSum(n) - oddSum(m) << endl;
}
}
#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
int m, n;
cin >> t;
while(t--){
cin >> n >> m;
int ans = 0;
if(n > m) swap(n, m);
for(int i=n;i<=m;i++){
if(i & 1) ans += i * i * i;
else ans += i * i;
}
cout << ans << '\n';
}
return 0;
}
下面作为给其他读者参考的答案吧,其实题主采纳的是下面的代码,之前回答考虑少了,然后输出的不是正确的,现在才对
#include<iostream>
using namespace std;
int oddSum(int n) {
return n * n * (2 * n * n - 1);
}
int evenSum(int n) {
return 2 * 2 * n * (n + 1) * (2*n + 1) / 6;
}
int main() {
int N, m, n;
int minOdd, maxOdd, minEven, maxEven;
cin >> N;
while (N--) {
cin >> m >> n;
if (m > n) swap(m, n);
// sum(x^2) | m n
// 1^2 + ... + n^2 = n*(n+1)*(2n+1)/6
// (2*1)^2 + ... + (2*n)^2 = 4 * ( 1^2 + ... + n^2) = 4 * n*(n+1)*(2n+1)/6
minEven = m-1;
while (minEven>0&&minEven % 2 == 1) {
minEven -= 1;
}
if (minEven < 0) minEven = 0;
maxEven = n;
while (maxEven % 2 == 1) {
maxEven -= 1;
}
if (maxEven < 0) maxEven = 0;
// 转换成序号
cout << - evenSum(minEven/2) + evenSum(maxEven/2) << " ";
// 奇数sum(x^3) | m n
// (2*1-1)^3 + ... + (2*n-1)^3 = n^2 * (2*n^2 -1)
minOdd = m-1;
while (minOdd>0&&minOdd % 2 == 0) {
minOdd -= 1;
}
if (minOdd < 0) minOdd = 0;
maxOdd = n;
while (maxOdd % 2 == 0) {
maxOdd -= 1;
}
if (maxOdd < 0) maxOdd = 0;
// 转换成序号
cout << - oddSum((minOdd+1)/2 ) + oddSum((maxOdd + 1) / 2) << endl;
}
}
#include <stdio.h>
#include <math.h>
int main()
{
int a = 0,b = 0,i = 0,count,tmp,j=0;
int arr[64];
printf("输入几组数据?:\n");
scanf("%d",&count);
tmp = count;
printf("输入每组的两个整数:\n");
while(tmp--)
{
scanf("%d %d",&arr[i],&arr[i+1]);
i += 2;
}
for(j-0;j<count*2;j++)
{
if(arr[j]%2)
{
a += pow(arr[j],3);
}
else
{
b +=pow(arr[j],2);
}
}
printf("所有偶数的平方和为:%d\n所有奇数的三次方和为:%d\n",b,a);
return 0;
}