前にBigInt for swift(swiftで記述したBigInt)を掲載しましたが、それをCに移植しました。とは言ってもxcode上で稼動し、慣れたswift風のコマンドになっています。ではなぜ?という話になるのですが、windowsやlinaxに移植する手間が少し楽になります。最終的にはMac,windows,Linax上で稼動することになります。
関数等(BigInt_for_C_swift)
// 1. 初期化・生成
let a = BigInt("1234567890123456789012345678901234567890")//巨大数初期化に対応
let c = BigInt(1234567890123456789)//19桁まで
// 2. 基本演算
var x = BigInt("1000")
var y = BigInt("24")
let add = x + y // 1024
let sub = x - y // 976
let mul = x * y // 24000
let div = x / y // 41
let mod = x % y // 16
// 3.比較演算(Bool)
x = BigInt("1000")
y = BigInt("25")
x == y //false
x != y //true
x < y //false
x <= y //false
x > y //true
x >= y //true
print(x >= y) //true
// 4.判定型(Bool)
let q = BigInt("-12")
q.isZero // false 0ならtrue
q.isEven // true 偶数ならtrue
q.isOdd // false 奇数ならtrue
q.isPositive // false 正の数ならtrue
q.isNegative // true 負の数ならtrue
print(q.isNegative)//true
// 5. 累乗・剰余累乗
let two = BigInt("2")
let power = two.pow(100) //2^100
print(power)// 1267650600228229401496703205376
let modp = two.modPow(exp: 100, mod: BigInt("2"))// → (2^100) mod 97
print(modp) //16
//6. GCD/LCM(最大公約数・最小公倍数)
let d = BigInt(42)
let e = BigInt(56)
let g = BigInt.gcd(d, e) // 14
let l = BigInt.lcm(d, e) // 168
print(g, l)
//7. 素数判定(Miller–Rabin法)(Bool)
let r = BigInt("32416190071")
print(r.isProbablePrime) // true
let s = BigInt("1000005")
print(s.isProbablePrime) // false
//8. 乱数・素数生成
let t = BigInt.random(digits: 100)// 100桁の乱数
let u = BigInt.random(in: BigInt(1000)...BigInt(9999)) //1000...9999間の乱数
print(t, u)
let v = BigInt.randomProbablePrime(digits: 50)// 50桁の素数
print(u, v)
//9. 進数変換・バイト列
let n = BigInt("123456789")//十進数
print(n.hexString) // "75bcd15" 16進数に変換
print(BigInt.fromHex("0xff")) // 255 16進数を十進数に変換
let bytes = n.toBytesBE()
let m = BigInt.fromBytesBE(bytes)
