很多大数做加减乘除运算的时候,不能用int这样的变量来存储,因为位数会非常大,所以需要用数组来存储,用char数组存储后,还需要将每个字符都用 -‘0’ 来转成int型,然后就像手算那样逐位相加。
但是用java的大数运算的包,写起程序来会方便很多。
原题链接: http://acm.hdu.edu.cn/showproblem.php?pid=1002
大意: 两个大数进行相加,输出最终的和。
用java的BigInteger类来做会简单很多,代码如下:
import java.math.*;//引入math包,
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
for(int i=1; i <= t; i++){
BigInteger a = scanner.nextBigInteger(); //BigInteger,BigDecimal
BigInteger b = scanner.nextBigInteger();
BigInteger c = a.add(b); //add 两大数相加
System.out.println("Case " + i + ":");
System.out.println(a.toString() + " + "+b.toString()+" = "+c.toString());
if(i!=t) System.out.println();
}
}
}
原题链接: http://acm.hdu.edu.cn/showproblem.php?pid=1042
大意: 求n的阶乘, n<1000,所以位数应该会近10000
再用java的包,这里是用的multiply这个乘法,代码如下:
import java.math.*;//引入math包,
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
int n = scanner.nextInt();
BigDecimal b = new BigDecimal(1);
BigDecimal a;
if(n==0) System.out.println("1");
else{
while(n>0){
a = new BigDecimal(n);
b = b.multiply(a);
n--;
}
System.out.println(b.toString());
}
}
}
}
原题链接: http://acm.hdu.edu.cn/showproblem.php?pid=1250
大意:类似斐波那契数列,n不是很大,所以用不着快速幂,矩阵快速幂求它的时候,一般是有取模运算的。这个题只是数比较大,重点是用大数:
import java.math.*;//引入math包,
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
int n = scanner.nextInt();
BigInteger ans;
BigInteger a, b, c, d;
a = BigInteger.valueOf(1); //怎么将BigInteger初始化为1,这里和BigDecimal不一样。
ans = b = c = d = a;
if(n<=4) System.out.println("1");
else{
for(int i=5; i <= n; i++){
ans = a.add(b.add(c.add(d)));
a = b;
b = c;
c = d;
d = ans;
}
System.out.println(ans);
}
}
}
}