我正在开发一种编程语言,今天我成功地实现了阶乘函数的编译(递归),但是由于整数类型的最大值限制,最大只能计算到12的阶乘。请问有哪些方法可以处理任意大小的整数?当前这个语言的运行方式是将代码转化为C++。
我正在开发一种编程语言,今天我成功地实现了阶乘函数的编译(递归),但是由于整数类型的最大值限制,最大只能计算到12的阶乘。请问有哪些方法可以处理任意大小的整数?当前这个语言的运行方式是将代码转化为C++。
class BigAssNumber {
private byte[] value;
// This constructor can handle numbers where overflows have occurred.
public BigAssNumber(byte[] value) {
this.value=normalize(value);
}
// Adds two numbers and returns the sum. Originals not changed.
public BigAssNumber add(BigAssNumber other) {
// This needs to be a byte by byte copy in newly allocated space, not pointer copy!
byte[] dest = value.length > other.length ? value : other.value;
// Just add each pair of numbers, like in a pencil and paper addition problem.
for(int i=0; i<min(value.length, other.value.length); i++)
dest[i]=value[i]+other.value[i];
// constructor will fix overflows.
return new BigAssNumber(dest);
}
// Fix things that might have overflowed 0,17,22 will turn into 1,9,2
private byte[] normalize(byte [] value) {
if (most significant digit of value is not zero)
extend the byte array by a few zero bytes in the front (MSB) position.
// Simple cheap adjust. Could lose inner loop easily if It mattered.
for(int i=0;i<value.length;i++)
while(value[i] > 9) {
value[i] -=10;
value[i+1] +=1;
}
}
}
}
我利用字节中的额外空间,以通用方式处理加法溢出问题。这种方法也适用于减法,并且在某些乘法上有所帮助。
在C++中没有简单的方法来实现。你需要使用外部库,例如GNU Multiprecision,或者使用本地支持任意大整数的不同语言,例如Python。
我的首选方法是使用当前的int类型来处理32位整数(或者可能将其更改为long long之类的内部类型,只要它可以继续使用相同的算法),然后当它溢出时,将其更改为存储为bignum,无论是我自己创建的还是使用外部库。但是,我觉得我需要在每个算术操作上检查溢出,这大约会增加2倍的开销。我该如何解决这个问题?