d186: 11461 - Square Numbers

  1. 1. 內容
  2. 2. 範例輸入
  3. 3. 範例輸出
  4. 4. 想法
  5. 5. 程式碼

CPE 一顆星選集 49 道必考題

題目連結:https://zerojudge.tw/ShowProblem?problemid=d186

內容

給定兩個整數 a, b(0 < a <= b <= 100000),求出 a, b 之間有多少個完全平方數。

a = b = 0 代表結束。

範例輸入

1 4
1 10
0 0

範例輸出

2
3

想法

先建一個陣列儲存該數是否為完全平方數,接著從 a 到 b 檢查陣列,計算共有幾個數符合條件。

程式碼

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false), cin.tie(nullptr)
using namespace std;

int main(){
fastio;
int a, b, c;
bool squ[100001];
memset(squ, 0, sizeof(squ));
for(int i = 1; i < 1000; ++i){
if(i*i < 100001){
squ[i*i] = true;
}
else break;
}
while(cin >> a >> b){
c = 0;
if(a == 0 && b == 0) break;
for(int i = a; i <= b; ++i){
if(squ[i]) ++c;
}
cout << c << "\n";
}
return 0;
}