#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;
}
这两种算法都可以判断一个数是否为完全平方数,第二种算法的效率更高一些。