java中封装了BigInteger(整数)类和BigDecimal(浮点数)类来解决大数问题
分别引用java.math.BigInteger和java.math.BigDecimal的包
BigInteger:
常量:BigInteger.ONE(1);BigInteger.ZERO(0);BigInteger.TEN(10)
函数:(1)p.add(BigInteger val) 返回p+val
(2)p.and(BigInteger val) 返回p&val
(3)p.compareTo(BigInteger val) 返回 -1(p
(4)p.divide(BigInteger val) 返回p/val(取整)
(5)p.mod(BigInteger val) 返回p%val(取模)
(6)p.remainder(BigInteger val) 返回p%val(取模)
(7)p.subtract(BigInteger val) 返回p-val
(8)p.multiply(BigInteger val) 返回p*val
(9)p.pow(int n) 返回p^n
(10)p.modPow(BigInteger n , BigInteger m ) 返回p^n%m
(11)p.gcd(BigInteger val) 返回p和val的最大公约数
(12)p.max(BigInteger val) 返回最大值
(13)p.min(BigInteger val) 返回最小值
(14)p.equals(BigInteger val) 返回true(相等)
(15)valueOf(long val) 返回转换成BigInteger类型的值
BigDecimal:
以上常量和函数在BigDecimal同样封装着
这里提2个对浮点数处理的函数:
(1)p.stripTrailingZeros() 去除p末尾多余的0
(2)p.toPlainString() 输出普通的字符串非科学计数法
hdu上几个大数的题目:
hdu 1063:
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static void main(String args[]){
Scanner cin = new Scanner(System.in);
int n; BigDecimal R;
while( cin.hasNext() ){
R = cin.nextBigDecimal();
n = cin.nextInt();
BigDecimal sum = R.pow(n);
String str = sum.stripTrailingZeros().toPlainString();
if( str.charAt(0) == '0' ) System.out.println(str.substring(1));
else System.out.println(str);
}
}
}
hdu 1297:
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static void main(String args[]){
Scanner cin = new Scanner(System.in);
BigInteger rec[] = new BigInteger[1005];
rec[1] = BigInteger.valueOf(1);
rec[2] = BigInteger.valueOf(2);
rec[3] = BigInteger.valueOf(4);
rec[4] = BigInteger.valueOf(7);
for( int i = 5 ; i <= 1001 ; ++i ){
rec[i] = rec[i-1].add(rec[i-2]).add(rec[i-4]);
}
while( cin.hasNext() ){
int n = cin.nextInt();
System.out.println(rec[n]);
}
}
}
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static void main(String args[]){
Scanner cin = new Scanner(System.in);
BigInteger rec[] = new BigInteger[1004];
rec[1] = BigInteger.valueOf(1);
rec[2] = BigInteger.valueOf(2);
for( int i = 3 ; i <= 1000 ; ++i ){
rec[i] = rec[i-1].add(rec[i-2]);
}
BigInteger n,m;
while( cin.hasNext() ){
n = cin.nextBigInteger();
m = cin.nextBigInteger();
if( n.equals(BigInteger.ZERO)&&m.equals(BigInteger.ZERO) ) break;
int count = 0;
for( int i = 1 ; i <= 1000 ; ++i ){
if( rec[i].compareTo(n)>=0&&rec[i].compareTo(m)<=0 ) ++count;
}
System.out.println(count);
}
}
}