ちまちま説明をするより、関数一覧が欲しいという方も多いと思うので、ここに載せます。
📘 BigInt.swift 関数・使用方法一覧
🔹 初期化
- init(_ value: String)
文字列から初期化
- let a = BigInt("12345")
let b: BigInt = "67890"
- init(_ value: Int)
整数から初期化
- let a = BigInt(42)
let b: BigInt = 99
- リテラル対応
- let a: BigInt = "123"
let b: BigInt = 456
🔹 出力
- description(CustomStringConvertible)
文字列化
- let a: BigInt = "789"
print(a) // 789
🔹 判定系
- isZero : 0 かどうか
- isPositive : 正の数か
- isNegativeValue : 負の数か
- isEven : 偶数か
- isOdd : 奇数か
let a: BigInt = "10"
print(a.isEven) // true
print(a.isOdd) // false
🔹 比較演算
- ==, <, >, <=, >=
- let a: BigInt = "100"
let b: BigInt = "200"
print(a < b) // true
🔹 四則演算
- +, -, *, /, %
- 複合代入: +=, -=, *=, /=, %=
- 単項マイナス: -a
let a: BigInt = "20"
let b: BigInt = "7"
print(a / b) // 2
print(a % b) // 6
🔹 数学関数
- BigInt.pow(a, n) : 累乗(a^n, nはInt ≥ 0)
- BigInt.modPow(a, e, m) : (a^e mod m)
- BigInt.sqrt(of: n) : 整数平方根 ⌊√n⌋
- BigInt.gcd(a, b) : 最大公約数
- BigInt.lcm(a, b) : 最小公倍数
- BigInt.factorial(n) : 階乗 (n!)
- BigInt.isPerfectSquare(n) : 完全平方数か判定
- BigInt.isProbablePrime(n, iterations) : Miller–Rabin 法による素数判定
let a: BigInt = "25"
print(BigInt.sqrt(of: a)) // 5
print(BigInt.gcd(42, 56)) // 14
print(BigInt.factorial(5)) // 120
🔹 乱数生成
- BigInt.random(digits: n) : n 桁の乱数
- BigInt.random(in: range) : 指定範囲の乱数
let r1 = BigInt.random(digits: 5) // 5桁ランダム
let r2 = BigInt.random(in: 10...1000) // 10~1000 の乱数
🔹 ユーティリティ
- digitCount : 桁数
- toHexString() : 16進数文字列に変換
- toIntSafe() : Int に収まれば Int を返す(オーバーフローなら nil)
let a: BigInt = "65535"
print(a.toHexString()) // "FFFF"
print(a.digitCount) // 5
print(a.toIntSafe()) // Optional(65535)
