在用C或者C++处理大数时感觉非常麻烦,但是在JAVA中有两个类BigInteger和BigDecimal分别表示大整数类和大浮点数类,至于两个类的对象能表示最大范围不清楚,理论上能够表示无线大的数,只要计算机内存足够大。
这两个类都在java.math.*包中,因此每次必须在开头处引用该包。
Ⅰ基本函数:
1.valueOf(parament); 将参数转换为制定的类型
比如 int a=3;
BigInteger b=BigInteger.valueOf(a);
则b=3;
String s=”12345”;
BigInteger c=BigInteger.valueOf(s);
则c=12345;
2.add(); 大整数相加
BigInteger a=new BigInteger(“23”);
BigInteger b=new BigInteger(“34”);
a. add(b);
3.subtract(); 相减
4.multiply(); 相乘
5.divide(); 相除取整
6.remainder();取余
7.pow(); a.pow(b)=a^b
8.gcd(); 最大公约数
9.abs(); 绝对值
10.negate();取反数
11.mod(); a.mod(b)=a%b=a.remainder(b);
12.max(); min();
13.punlic int comareTo();
14.boolean equals(); 是否相等
15.BigInteger构造函数:
一般用到以下两种:
BigInteger(String val);
将指定字符串转换为十进制表示形式;
BigInteger(String val,int radix);
将指定基数的BigInteger的字符串表示形式转换为BigInteger
Ⅱ.基本常量:
A=BigInteger.ONE 1
B=BigInteger.TEN 10
C=BigInteger.ZERO 0
Ⅲ.基本操作
1. 读入:
用Scanner类定义对象进行控制台读入,Scanner类在java.util.*包中
Scanner cin=new Scanner(System.in);// 读入
while(cin.hasNext()) //等同于!=EOF
{
int n;
BigInteger m;
n=cin.nextInt(); //读入一个int;
m=cin.BigInteger();//读入一个BigInteger;
System.out.print(m.toString());
}
Ⅳ.运用
四则预算:
import java.util.Scanner;
import java.math.*;
import java.text.*;
public class Main
{
public static void main(String args[])
{
Scanner cin = new Scanner ( System.in );
BigInteger a,b;
int c;
char op;
String s;
while( cin.hasNext() )
{
a = cin.nextBigInteger();
s = cin.next();
op = s.charAt(0);
if( op == '+')
{
b = cin.nextBigInteger();
System.out.println(a.add(b));
}
else if( op == '-')
{
b = cin.nextBigInteger();
System.out.println(a.subtract(b));
}
else if( op == '*')
{
b = cin.nextBigInteger();
System.out.println(a.multiply(b));
}
else
{
BigDecimal a1,b1,eps;
String s1,s2,temp;
s1 = a.toString();
a1 = new BigDecimal(s1);
b = cin.nextBigInteger();
s2 = b.toString();
b1 = new BigDecimal(s2);
c = cin.nextInt();
eps = a1.divide(b1,c,4);
//System.out.println(a + " " + b + " " + c);
//System.out.println(a1.doubleValue() + " " + b1.doubleValue() + " " + c);
System.out.print( a.divide(b) + " " + a.mod(b) + " ");
if( c != 0)
{
temp = "0.";
for(int i = 0; i < c; i ++) temp += "0";
DecimalFormat gd = new DecimalFormat(temp);
System.out.println(gd.format(eps));
}
else System.out.println(eps);
}
}
}
}
/**
* @author zhangyong
*
*/
public class BigInt {
/**
* @param args
*/
public static void main(String[] args) {
BigInt b = new BigInt();
b.add("999", "999");
}
public String add(String a, String b) {
//检查输入
if (!a.matches("\d+") || !a.matches("\d+")) {
return null;
}
final int BASE = 10;//10进制
int lenA = a.length();//加数的长度
int lenB = b.length();//被加数的长度
int maxLen, partialSum, carry = 0;//大数的长度,和,进位
maxLen = (lenA > lenB) ? lenA : lenB;
StringBuffer sum = new StringBuffer();
int temA, temB = 0;
for (int i = 0; i < maxLen; i++) {
if (i >= lenA) {
temA = 0;
} else {
temA = Integer.valueOf(a.charAt(lenA - i - 1) - 48);
}
if (i >= lenB) {
temB = 0;
} else {
temB = Integer.valueOf(b.charAt(lenB - i - 1) - 48);
}
partialSum = temA + temB + carry;
carry = partialSum / BASE;
sum.append(partialSum % BASE);
}
if (carry == 1)
sum.append(carry);
System.out.println(a + "+" + b + "=" + sum.reverse().toString());
return sum.reverse().toString();
}
}
package test;
public class VeryBigNumAdd {
public static void main(String[] args) {
VeryBigNumAdd vbn = new VeryBigNumAdd();
String a = "123453243455535634535252345234677576252241234123523453664563634";
String b = "123453243455535634535252345234677576252241234123523453664563634";
String result = vbn.doAdd(a, b);
System.out.println("result:" + result);
}
String doAdd(String a, String b) {
String str = "";
int lenA = a.length();
int lenB = b.length();
int maxLen = (lenA > lenB) ? lenA : lenB;
int minLen = (lenA < lenB) ? lenA : lenB;
String strTmp = "";
for (int i = maxLen - minLen; i > 0; i--) {
strTmp += "0";
}
// 把长度调整到相同
if (maxLen == lenA) {
b = strTmp + b;
} else
a = strTmp + a;
int JW = 0;// 进位
for (int i = maxLen - 1; i >= 0; i--) {
int tempA = Integer.parseInt(String.valueOf(a.charAt(i)));
int tempB = Integer.parseInt(String.valueOf(b.charAt(i)));
int temp;
if (tempA + tempB + JW >= 10 && i != 0) {
temp = tempA + tempB + JW - 10;
JW = 1;
} else {
temp = tempA + tempB + JW;
JW = 0;
}
str = String.valueOf(temp) + str;
}
return str;
}
}
import java.util.ArrayList;
import java.util.Collections;
public class VeryLongInt {
ArrayList digits;
// Postcondition: The VeryLongInt is empty.
public VeryLongInt() {
final int INITIAL_CAPACITY = 500;
digits = new ArrayList(INITIAL_CAPACITY);
} // default constructor
// Precondition: n >= 0.
// Postcondition: The VeryLongInt has been initialized from the
// not-very-long int n.
public VeryLongInt(int n) {
final int BASE = 10;
digits = new ArrayList();
do {
digits.add(new Integer(n % BASE));
n = n / BASE;
} // while
while (n > 0);
// digits is now in reverse order, so we reverse:
Collections.reverse(digits);
} // constructor
// Postcondition: The number of elements in the VeryLongInt has
// been returned.
public int size() {
return digits.size();
} // method size
// Precondition: The string s consists of a sequence of characters
// with non-digit characters ignored.
// There are no leading zeroes, except for 0
// itself, which has a single '0'.
// Postcondition: The VeryLongInt has been initialized from s.
public VeryLongInt(String s) {
final char LOWEST_DIGIT_CHAR = '0';
final char HIGHEST_DIGIT_CHAR = '9';
digits = new ArrayList(s.length());
char c;
int digit;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if ((LOWEST_DIGIT_CHAR <= c) && (c <= HIGHEST_DIGIT_CHAR)) {
digit = c - LOWEST_DIGIT_CHAR;
digits.add(new Integer(digit));
} // if a digit
} // for
} // constructor with string parameter
// Postcondition: The VeryLongInt has been returned as a string of digits.
public String toString() {
final String EMPTY_STRING = "";
String s = EMPTY_STRING;
for (int i = 0; i < digits.size(); i++)
s += digits.get(i);
return s;
} // method toString
// Postcondition: If i >= digits.size(), 0 has been returned; else
// the ith least significant digit in digits has
// been returned. The least significant digit is
// the 0th least significant digit.
private int least(int i) {
if (i >= digits.size())
return 0;
else
return ((Integer) (digits.get(digits.size() - i - 1))).intValue();
} // least
// Postcondition: The VeryLongInt has been incremented by otherVeryLong.
public void add(VeryLongInt otherVeryLong) {
final int BASE = 10;
int largerSize, partialSum, carry = 0;
VeryLongInt sum = new VeryLongInt();
if (digits.size() > otherVeryLong.digits.size())
largerSize = digits.size();
else
largerSize = otherVeryLong.digits.size();
for (int i = 0; i < largerSize; i++) {
partialSum = least(i) + otherVeryLong.least(i) + carry;
carry = partialSum / BASE;
sum.digits.add(new Integer(partialSum % BASE));
} // for
if (carry == 1)
sum.digits.add(new Integer(carry));
Collections.reverse(sum.digits);
digits = sum.digits;
} // method add
// Postcondition: A copy of the calling object has been returned.
public Object clone() {
VeryLongInt temp = new VeryLongInt();
temp.digits = (ArrayList) digits.clone();
return temp;
} // method clone
// Postcondition: true has been returned if the
// value of the VeryLongInt is less than the value
// of otherVeryLong. Otherwise, false
// has been returned.
public boolean less(VeryLongInt otherVeryLong) {
if (digits.size() < otherVeryLong.digits.size())
return true;
if (digits.size() > otherVeryLong.digits.size())
return false;
for (int i = 0; i < digits.size(); i++) {
if (((Integer) (digits.get(i))).intValue() < ((Integer) (otherVeryLong.digits
.get(i))).intValue())
return true;
if (((Integer) (digits.get(i))).intValue() > ((Integer) (otherVeryLong.digits
.get(i))).intValue())
return false;
} // for
return false; // the two objects have the same value
} // method less
// Postcondition: true has been returned if the value of the VeryLongInt
// is greater than the value of otherVeryLong. Otherwise,
// false has been returned.
public boolean greater(VeryLongInt otherVeryLong) {
return otherVeryLong.less(this);
} // method greater
// Postcondition: true has been returned if the value of the VeryLongInt
// is equal to the value of otherVeryLong. Otherwise,
// false has been returned.
public boolean equals(VeryLongInt otherVeryLong) {
return !less(otherVeryLong) && !otherVeryLong.less(this);
} // method equals
// Precondition: n > 0.
// Postcondition: The calling object contains the nth Fibonacci
// number.
public void fibonacci(int n) {
VeryLongInt previous = new VeryLongInt(1), current = new VeryLongInt(1), temp = new VeryLongInt();
digits.clear();
if (n <= 2)
digits.add(new Integer(1));
else {
for (int i = 3; i <= n; i++) {
temp = (VeryLongInt) current.clone();
current.add(previous);
previous = temp;
} // for
digits = current.digits;
} // else
} // method fibonacci
} // class VeryLongInt
发表评论 取消回复