用 C 实现了几个常用的数字相关的算法:
- 快速幂求整数次方。
- 辗转相处求最大公约数。
- 判断是否为素数。
// 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);
}
}
}