数字相关算法实现

用 C 实现了几个常用的数字相关的算法:

  1. 快速幂求整数次方。
  2. 辗转相处求最大公约数。
  3. 判断是否为素数。
// Filename: algorithm.h
// Created by lbt on 2020-9-21.
// Description: head file of number algorithm

#ifndef NUM_ALGORITHM_ALGORITHM_H
#define NUM_ALGORITHM_ALGORITHM_H
# include<stdbool.h>

double Pow(double a, int b);
int Gcd(int a, int b);
bool IsPrimeNumber(int a);

#endif //NUM_ALGORITHM_ALGORITHM_H

// Filename: algorithm.c
// Created by lbt on 2020-9-21.
// Description: source of number algorithm
#include "algorithm.h"

// 快速幂求整数次方
// 输入: double a, 底数
//      int b, 指数
// 输出: double, a^b
double Pow(double a, int b){
    switch(b){
        case 1: return a;
        case -1: return 1.0 / a;
        case 0: return 1;
    }
    double res = Pow(a, b >> 1) * Pow(a, b >> 1) * Pow(a, b % 2);
    return res;
}

// 辗转相处求两个整数的最大公约数
// 输入: int a
//      int b
// 输出: a 和 b 的最大公约数
int Gcd(int a, int b){
    if(a == 0 || b == 0){
        return 0;
    }
    while(a % b != 0){
        int temp = b;
        b = a % b;
        a = temp;
    }
    return b;
}

// 判定整数是否为素数
// 输入: int a
// 输出: bool, false 代表 a 不是素数,true 相反
bool IsPrimeNumber(int a){
    if(a < 2){
        return false;
    }

    int i;
    for(i = 2; i*i <= a; i++){
        if(a % i == 0){
            return false;
        }
    }
    return true;
}
// Filename: main.c
// Create by lbt on 2020-9-21.
// Description: test number algorithm

#include <stdio.h>
#include "algorithm.h"
int main() {
    int a = 81, b = 6;
    printf("Gcd of %d and %d is %d.\n", a, b, Gcd(a, b));
    printf("%d^%d = %.4f\n", a, b, Pow(a, b));
    for(a = 2; a < 100; a++){
        if(IsPrimeNumber(a)){
            printf("%d\t", a);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值