日期:2026年4月25日
ZeroJudge 題目連結:d186. 11461 - Square Numbers
解題想法
先將 $a$ 開根號並向上取整,計算範圍內平方數開根根號的最小值 $low$,再對 $b$ 開根號並向下取整,計算範圍內平方數開根根號的最大值 $high$,答案就是 $high - low + 1$。
Python 程式碼
使用時間約為 7 ms,記憶體約為 8.6 MB,通過測試。
def solve():
import sys, math
result = []
data = sys.stdin.read().split()
ptr = 0
while ptr < len(data):
a, b = map(int, data[ptr:ptr+2])
ptr += 2
if a == 0 and b == 0: break
low = math.ceil(math.sqrt(a))
high = math.floor(math.sqrt(b))
result.append(f"{high - low + 1:d}\n")
sys.stdout.write("".join(result))
if __name__ == "__main__":
solve()
C++ 程式碼
使用時間約為 0 ms,記憶體約為 1.9 MB,通過測試。
#include <cstdio>
#include <cmath>
int main() {
int a, b;
while(scanf("%d %d", &a, &b) != EOF) {
if (a == 0 && b == 0) break;
int low = (int)ceil(sqrt(a));
int high = (int)sqrt(b);
printf("%d\n", high - low + 1);
}
return 0;
}
沒有留言:
張貼留言