Swift-BigInt 是 Swift 5 的轻量级易于使用的任意精度算术库。
它支持大多数常见数学运算符的整数(BInt)和分数(BDouble)。 还实现了优化的数学函数,例如阶乘或gcd,并可通过 BIntMath 访问。
计算 斐波那契数列(Fibonacci sequence),不受长整型位数限制。
从 https://codeload.github.com/mkrd/Swift-BigInt/zip/refs/heads/master
下载 Swift-BigInt-master.zip 解压后请看 Swift-BigInt-master/docs/index.html
cd D:\Swift\test
mkdir fibonacci
cd fibonacci
swift package init --type executable
Creating executable package: fibonacci
Creating Package.swift
Creating .gitignore
Creating Sources/
Creating Sources\main.swift
---
编写 Sources\main.swift 如下
// The Swift Programming Language
// file:///D:/Swift/test/Swift-BigInt-master/docs/index.html
import Foundation
import BigNumber
var i:Int = 0
if CommandLine.arguments.count > 1 {
let str = CommandLine.arguments[1]
let number = NumberFormatter().number(from: str)
i = number!.intValue
} else {
print(" usage: fibonacci.exe n ")
exit(0)
}
// 计算 斐波那契数列(Fibonacci sequence)
func fib(n: Int) -> BInt {
if n <= 0 { return 0 }
var x: BInt = 0, y: BInt = 1
for _ in 1..<n {
(x, y) = (y, y + x)
}
return y
}
// 调用示例
print("fib(\(i))=", fib(n:i))
编写 fibonacci\Package.swift 如下
// swift-tools-version: 5.10
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "fibonacci",
//products: [ ],
dependencies: [
.package(url: "https://github.com/mkrd/Swift-BigInt.git", branch: "master")
],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
// Targets can depend on other targets in this package and products from dependencies.
.executableTarget(
name: "fibonacci",
dependencies: [ ],
plugins: [
.plugin(name: "BigNumber", package: "Swift-BigInt"),
]),
]
)
cd fibonacci
编译当前包及其依赖项:
swift build
D:\Swift\test\fibonacci>swift build
Building for debugging...
[13/13] Linking D:\Swift\test\fibonacci\.build\x86_64-unknown-windows-msvc\debug\fibonacci.exe
Build complete! (28.21s)
warning: unable to create symbolic link at D:\Swift\test\fibonacci\.build\debug:
cd D:\Swift\test\fibonacci\.build\x86_64-unknown-windows-msvc\debug\
运行 fibonacci.exe 200
fib(200)= 280571172992510140037611932413038677189525
运行 fibonacci.exe 1000
fib(1000)= ......
用 python 校验,以上结果正确:
python fibonacci.py 200
fib1(200)= 280571172992510140037611932413038677189525
这是本人练习笔记,仅供同学参考。