作为一名自学成才的程序员,我不知道像gmp这样的库,并且自己编写了几个“Big Integer”函数来处理大整数运算。驱动我的算法的关键思想是将我感兴趣的大整数存储在一个数组中(即每个索引代表一个数字的数字(例如123456789将在数组中如下:(1,2,3,4,5, 6,7,8,9))。下面是一个大整数加法的例子。
MyBigIntegerAddition <- function(x1, x2) {
MyNum1 <- as.integer(strsplit(as.character(x1), "")[[1]])
MyNum2 <- as.integer(strsplit(as.character(x2), "")[[1]])
if (length(MyNum1) < length(MyNum2)) {
while (length(MyNum1) < length(MyNum2)) {MyNum1 <- c(0L, MyNum1)}
} else if (length(MyNum2) < length(MyNum1)) {
while (length(MyNum2) < length(MyNum1)) {MyNum2 <- c(0L, MyNum2)}
}
MyNum1 <- MyNum1 + MyNum2
lenMyNum1 <- length(MyNum1)
if (lenMyNum1 >= 2L) {
for (j in lenMyNum1:2L) {
TempB1 <- MyNum1[j] %% 10L
TempB2 <- floor(MyNum1[j]/ 10L)
MyNum1[j] <- TempB1
MyNum1[j - 1L] <- MyNum1[j - 1L] + TempB2
}
}
while ((MyNum1[1L] / 10L) > 1L) {
TempB1 <- MyNum1[1L] %% 10L
TempB2 <- floor(MyNum1[1L]/ 10L)
MyNum1[1L] <- TempB1
MyNum1 <- c(TempB2, MyNum1)
}
paste(MyNum1, collapse = "")
}
以下是比较输出
的随机示例MyBigIntegerAddition("103489710232857289034750289347590984710923874","2987234756 23746529875692873456927834569298347569237")
[1] "298723579113456762732981908207217182160283058493111"
> add.bigz("103489710232857289034750289347590984710923874","298723475623746529875692873456927834569298347569237")
Big Integer ('bigz') :
[1] 298723579113456762732981908207217182160283058493111
我提供了一个验证我的结果的功能。
TestStringMath <- function(n,Lim1,Lim2) {
samp1 <- sample(Lim1:Lim2,n)
samp2 <- sample(Lim1:Lim2,n)
count <- 0L
for (i in 1:n) {
temp1 <- add.bigz(samp1[i], samp2[i])
temp2 <- as.bigz(MyBigIntegerAddition(samp1[i], samp2[i]))
if (!(temp1==temp2)) {
count <- count+1L
}
}
count
}
问题: gmp的算术功能究竟是如何工作的?他们将数字转换为字符串并使用数组吗?他们只是调用更多的记忆吗?