温馨提示×

C语言完全平方数算法有哪些

小樊
99
2024-06-20 01:18:26
栏目: 编程语言

  1. 暴力法:遍历所有可能的完全平方数,判断是否等于给定的数。
#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;
}
  1. 二分查找法:利用二分查找的思想,在范围内查找给定数的平方根,判断是否为完全平方数。
#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;
}

这两种算法都可以判断一个数是否为完全平方数,第二种算法的效率更高一些。

0