【題解】ZeroJudge d186: 11461 – Square Numbers

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=d186
【解題想法】

  • [a, b] 之間的「完全平方數」數目 = [ ceil( sqrt(a) ), floor( sqrt(b) ) ] 間有幾個正整數。
#include <iostream>
#include <cmath>
using namespace std;
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int a, b;
    while (cin >> a >> b && a + b){
        int n1 = sqrt(a);
        int n2 = sqrt(b);
        if (n1*n1 != a) n1++;
        cout << n2 - n1 + 1 << "\n";
    }
    return 0;
}

Python code (credit: Amy Chou)

while True:
    a, b = map(int, input().split())
    if a + b == 0:
        break
    
    n1 = int(a ** 0.5)
    n2 = int(b ** 0.5)
    if n1 * n1 != a:
        n1 += 1
    print(n2 - n1 + 1)
分享本文 Share with friends