- 暴力法:遍历所有可能的完全平方数,判断是否等于给定的数。
#includeint 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; }
- 二分查找法:利用二分查找的思想,在范围内查找给定数的平方根,判断是否为完全平方数。
#includeint 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; }
这两种算法都可以判断一个数是否为完全平方数,第二种算法的效率更高一些。