平方和与立方和
Problem Description
给定一段连续的整数,求出他们中所有偶数的平方和以及所有奇数的立方和。
Input
输入数据包含多组测试实例,每组测试实例包含一行,由两个整数m和n组成。
Output
对于每组输入数据,输出一行,应包括两个整数x和y,分别表示该段连续的整数中所有偶数的平方和以及所有奇数的立方和。
你可以认为32位整数足以保存结果。
Sample Input
1 3
2 5
Sample Output
4 28
20 152
Author
lcy
Source
C语言程序设计练习(一)
解题思路
要点在于给出的两个整数不一定是由小到大,需要考虑。
AC
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int m, n, j, o;
while (cin >> m >> n) {
if (m > n) swap(m, n);
j = 0, o = 0;
for (int i = m; i <= n; i++) {
if (i % 2 == 1)j += pow(i, 3);
else o += pow(i, 2);
}
cout << o << " " << j << endl;
}
return 0;
}
2024.02.27
#include<stdio.h>
#include<iostream>
using namespace std;
int main() {
int start, end, odd, even;
while (scanf("%d %d", &start, &end) != EOF) {
if (start > end)
swap(start, end);
even = 0;
odd = 0;
for (int i = start; i <= end; i++) {
if (i % 2 == 0)
even += i * i;
else
odd += i * i * i;
}
printf("%d %d\n", even, odd);
}
return 0;
}