【C】库函数之 pow

目录

1. Raise to power

2. 两种实现

2.1 递归

2.2 迭代

3. 测试函数

4. 输出结果


1. Raise to power

#include <math.h>
double pow(double base, double exponent);

Returns base raised to the power exponent:

base ^ exponent

以上是 cplusplus 对 pow 函数的介绍,可以看出该函数用来计算 base 的 exponent 次幂。

本篇实现的 pow 函数仅支持幂次为 int 类型:

double pow(double base, int exponent);

2. 两种实现

有兴趣的话可以在 leetcode-50 提交:

2.1 递归

以 2^3 为例,假设 2^3 比较难求,那么可以将 2^3 转换为 2 * 2^2,这样只需要先求出 2^2,同理,2^2 又可以转换为 2 * 2^1,而 2^1 也可以转换为 2 * 2^0,

假如幂次是负数,可以将其转换为正数求解。(ps:这里 2^3 表示 2 的 3 次方,不是按位异或)

double myPow(double base, long long exponent) {
    if (0 == exponent)
        return 1.0;

    if (1 == exponent)
        return base;

    //double num = myPow(base, exponent / 2); // 二分
    double num = myPow(base, exponent >> 1);

    //return 0 == exponent % 2 ? num * num : num * num * base; // 如果二分后是奇数则需要 再乘以 base
    return exponent & 0x1 ? num * num * base : num * num;
}

double Pow(double base, int exponent) {
    long long l_num = n;

    return l_num >= 0 ? myPow(base, l_num) : 1.0 / myPow(base, -l_num);
}

2.2 迭代

幂次自减作为循环条件,这里需要注意的是幂次为负数时,需要先将幂次转换为其相反数。

double myPow(double base, long long exponent) {
    double ret = 1.0, d = base;
     
    while (exponent > 0) {
        if (1 == (exponent & 0x1))
            ret *= d;
     
        d *= d;
        exponent /= 2;
    }   
     
    return ret;
}    
     
double Pow(double base, int exponent) {
    long long l_num = exponent;
     
    return l_num >= 0 ? myPow(base, l_num) : 1.0 / myPow(base, -l_num);
}

3. 测试函数

#include <stdio.h>
#include <limits.h>

void test() {
    printf("%g ^ %d = %g\n", 2.0, 0, Pow(2.0, 0));
    printf("%g ^ %d = %g\n", 2.1, 0, Pow(2.1, 0));
    printf("%g ^ %d = %g\n", 2.0, 1, Pow(2.0, 1));
    printf("%g ^ %d = %g\n", 2.1, 1, Pow(2.1, 1));
    printf("%g ^ %d = %g\n", 2.0, 3, Pow(2.0, 3));
    printf("%g ^ %d = %g\n", 2.1, 3, Pow(2.1, 3));
    printf("%g ^ %d = %g\n", 2.0, -2, Pow(2.0, -2));
    printf("%g ^ %d = %g\n", 2.1, -3, Pow(2.1, -3));
    printf("%g ^ %d = %g\n", -2.0, 3, Pow(-2.0, 3));
    printf("%g ^ %d = %g\n", -2.1, 3, Pow(-2.1, 3));
    printf("%g ^ %d = %g\n", 0.00001, INT_MAX, Pow(0.00001, INT_MAX));
    printf("%g ^ %d = %g\n", 1.00000, INT_MIN, Pow(1.00000, INT_MIN));
}
 
int main(void) {
    test();
 
    return 0;
}

4. 输出结果

2 ^ 0 = 1
2.1 ^ 0 = 1
2 ^ 1 = 2
2.1 ^ 1 = 2.1
2 ^ 3 = 8
2.1 ^ 3 = 9.261
2 ^ -2 = 0.25
2.1 ^ -3 = 0.10798
-2 ^ 3 = -8
-2.1 ^ 3 = -9.261
1e-05 ^ 2147483647 = 0
1 ^ -2147483648 = 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值