溫馨提示×

C語言完全平方數怎樣高效編碼

小樊
85
2024-06-20 01:19:26
欄目: 編程語言

以下是一個高效的C語言代碼示例,用于判斷一個數是否是完全平方數:

#include <stdio.h>

int isPerfectSquare(int num) {
    if (num < 0) {
        return 0;
    }
    
    int i = 1;
    while (num > 0) {
        num -= i;
        i += 2;
    }
    
    return num == 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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女