題目連結 http://zerojudge.tw/ShowProblem?problemid=a059。
演算法如下:
找出在範圍 [a, b]內大於或等於 a 的完全平方數(sqrt),與 a 的平方根(k)。當 sqrt小於或等於 b 時{ 將 sqrt加到 sum裡 k+= 1 sqrt= k* k}
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
int t, a, b;
cin >> t;
int sum[t];
int i = 0;
do {
cin >> a;
cin >> b;
int k = 1;
int sqrt = 1;
sum [i] = 0;
while(sqrt < a) {
k++;
sqrt = k * k;
}
//cout << "S:" << sqrt << endl;
if( sqrt <= b)
sum[i] = sqrt;
else
sum[i] = 0;
k++;
sqrt = k * k;
while(sqrt <= b) {
// cout << "S:" << sqrt << endl;
sum[i] += sqrt;
k++;
sqrt = k * k;
}
//cout << sum[i] << endl << endl;
i++;
} while(i < t);
for(i = 0; i < t; i++)
{
cout << "Case " << i + 1 << ": " << sum[i] << endl;
}
return 0;
}
沒有留言:
張貼留言