#include <stdio.h>
int isPerfectSquare(int num) {
for (int i = 1; i * i <= num; i++) {
if (i * i == num) {
return 1;
}
}
return 0;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (isPerfectSquare(num)) {
printf("%d is a perfect square.\n", num);
} else {
printf("%d is not a perfect square.\n", num);
}
return 0;
}
#include <stdio.h>
int isPerfectSquare(int num) {
long left = 1, right = num;
while (left <= right) {
long mid = left + (right - left) / 2;
long square = mid * mid;
if (square == num) {
return 1;
} else if (square < num) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return 0;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (isPerfectSquare(num)) {
printf("%d is a perfect square.\n", num);
} else {
printf("%d is not a perfect square.\n", num);
}
return 0;
}
這兩種算法都可以判斷一個數是否為完全平方數,第二種算法的效率更高一些。