Handling high precision problems with Java

tags: Large number  Java  High precision

Handling high-precision (large number) problems with Java


Specification input/output in Java

Input (Fuck the stupid Easyin)

import java.util.Scanner;
class InputTest {
    public static void main(String[] args) {
       	Scanner sc = new Scanner(System.in);
        	/////Save the entered value in the variable //////
       	int i1 = sc.nextInt();
       	double d1 = sc.nextDouble();
       	char c1 = sc.next().charAt(0);
       	String str1 = sc.nextLine();
       	/////Use a lot, explore on your own /////
        	///// After using it, be careful to turn off Scanner //////
        	sc.close();
    }
}

Output

class OutPutTest {
	public static void main(String[] args) {
        System.out.println("hello, world"); // Wrap after output
        System.out.print("hello, world"); // Do not wrap after output
        System.out.printf("%s\n", "hello, world"); / / Shaped as c language standard output
	}
}

Two objects (not noticed)

BigInteger

public class BigInteger
extends Number
implements Comparable<BigInteger>

An immutable integer of arbitrary precision. In all operations, BigInteger (such as Java's basic integer type) is represented in two's complement form. BigInteger provides the counterpart of all Java's basic integer operators and provides all the relevant methods of java.lang.Math. In addition, BigInteger provides the following operations: modular arithmetic, GCD calculations, prime tests, prime generation, bit manipulation, and a few other operations.

Field summary

type of data Attributes Interpretation
static Biginteger ONE Constant 1
static BigInteger TEN Constant 10
static BigInteger ZERO Constant 0

Summary of construction methods

Method name and parameter list Interpretation
BigInteger (byte[] val) Converts a byte array containing the two's complement representation of BigInteger to BigInteger.
BigInteger (int signum, byte[] magnitude) Converts the symbol-quantity representation of BigInteger to BigInteger.
BigInteger (int bitLength, int certainty, Random rnd) Constructs a randomly generated positive BigInteger, which may be a prime number with the specified bitLength.
BigInteger (int numBits, Random rnd) Construct a randomly generated BigInteger, which is in0 To(2numBits - 1)(including) values ​​that are evenly distributed over the range.
BigInteger (String val) Converts the decimal representation of BigInteger to BigInteger.
BigInteger (String val, int radix) Converts the string representation of the specified cardinality BigInteger to BigInteger.

Method summary

Return value type Method name and parameter list Interpretation
BigInteger abs() Returns a BigInteger whose value is the absolute value of this BigInteger .
BigInteger add(BigInteger val) Return its value(this + val) BigInteger.
BigInteger and(BigInteger val) Return its value(this & val) BigInteger.
BigInteger andNot(BigInteger val) Return its value(this & ~val) BigInteger.
int bitCount() Returns the number of bits in the two's complement representation of this BigInteger that differ from the symbol.
int bitLength() Returns the number of bits in the smallest two's complement representation of this BigInteger, excluding the sign bit.
BigInteger clearBit(int n) Returns a BigInteger whose value is equivalent to this BigInteger with the specified bit cleared.
int compareTo(BigInteger val) Compare this BigInteger with the specified BigInteger.
BigInteger divide(BigInteger val) Return its value(this / val) BigInteger.
BigInteger[] divideAndRemainder(BigInteger val) Return contains(this / val) Heel(this % val) An array of two BigIntegers.
double doubleValue() Convert this BigInteger todouble
boolean equals(Object x) Compares this BigInteger with the specified Object for equality.
BigInteger flipBit(int n) Returns a BigInteger whose value is equivalent to the value of the specified bit inversion for this BigInteger.
float floatValue() Convert this BigInteger tofloat
BigInteger gcd(BigInteger val) Returns a BigInteger whose value isabs(this) with abs(val)The greatest common divisor.
int getLowestSetBit() Returns the index of the rightmost (lowest bit) 1 bit of this BigInteger (ie the number of 0 bits from the right end of this byte to the rightmost 1 bit in this byte).
int hashCode() Returns a hash of this BigInteger .
int intValue() Convert this BigInteger toint
boolean isProbablePrime(int certainty) If this BigInteger might be prime, then returntrueIf it must be a composite number, then returnfalse
long longValue() Convert this BigInteger tolong
BigInteger max(BigInteger val) Return this BigInteger andval The maximum value.
BigInteger min(BigInteger val) Return this BigInteger andval The minimum value.
BigInteger mod(BigInteger m) Return its value(this mod m) BigInteger.
BigInteger modInverse(BigInteger m) Return its value(this-1 mod m) BigInteger.
BigInteger modPow(BigInteger exponent, BigInteger m) Return its value(thisexponent mod m) BigInteger.
BigInteger multiply(BigInteger val) Return its value(this val) BigInteger.
BigInteger negate() Return its value is(-this) BigInteger.
BigInteger nextProbablePrime() Return is greater than thisBigInteger It may be the first integer of the prime number.
BigInteger not() Return its value(~this) BigInteger.
BigInteger or(BigInteger val) Return its value(this | val) BigInteger.
BigInteger pow(int exponent) Return its value(thisexponent) BigInteger.
static BigInteger probablePrime(int bitLength, Random rnd) Returns a positive BigInteger with a specified length, possibly a prime number.
BigInteger remainder(BigInteger val) Return its value(this % val) BigInteger.
BigInteger setBit(int n) Returns a BigInteger whose value is equivalent to this BigInteger with the specified bit set.
BigInteger shiftLeft(int n) Return its value(this << n) BigInteger.
BigInteger shiftRight(int n) Return its value(this >> n) BigInteger.
int signum() Returns the sign function of this BigInteger .
BigInteger subtract(BigInteger val) Return its value(this - val) BigInteger.
boolean testBit(int n) Return if and only if the specified bit is settrue
byte[] toByteArray() Returns a byte array containing the two's complement representation of this BigInteger .
String toString() Returns the decimal string representation of this BigInteger .
String toString(int radix) Returns a string representation of the given cardinality of this BigInteger .
static BigInteger valueOf(long val) Return its value equal to the specifiedlong The value of BigInteger.
BigInteger xor(BigInteger val) Return its value(this ^ val) BigInteger.

BigDecimal

public class BigDecimal
extends Number
implements Comparable<BigDecimal>

Immutable, arbitrary precision signed decimal number.BigDecimal Consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits after the decimal point. If it is negative, multiply the unscaled value of the number by the negative power of 10 . therefore,BigDecimal The value represented is(unscaledValue × 10-scale)

BigDecimal Classes provide the following operations: arithmetic, scaling operations, rounding, comparison, hashing, and format conversion.toString() Method provisionBigDecimal Normative representation.

Field summary

type of data Attributes Interpretation
static BigDecimal ONE The value is 1, and the scale is 0.
static int ROUND_CEILING Close to the rounding mode of positive infinity.
static int ROUND_DOWN Rounding mode close to zero.
static int ROUND_FLOOR Rounding mode close to negative infinity.
static int ROUND_HALF_DOWN Rounds to the "closest" number, rounded up if rounded to the distance between two adjacent numbers.
static int ROUND_HALF_EVEN Rounds to the "closest" number, rounding to an adjacent even number if the distance to two adjacent numbers is equal.
static int ROUND_HALF_UP Rounds to the "closest" number, rounded up if rounded to the distance between two adjacent numbers.
static int ROUND_UNNECESSARY Asserting the requested operation has an accurate result, so no rounding is required.
static int ROUND_UP Rounds rounding mode away from zero.
static BigDecimal TEN The value is 10 and the scale is 0.
static BigDecimal ZERO The value is 0 and the scale is 0.

Summary of construction methods

Method name and parameter list Interpretation
BigDecimal(BigInteger val) WillBigInteger Convert toBigDecimal
BigDecimal(BigInteger unscaledVal, int scale) WillBigInteger Unscaled value andint Scale converted toBigDecimal
BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) WillBigInteger Unscaled value andint Scale converted toBigDecimal(rounding according to the context setting).
BigDecimal(BigInteger val, MathContext mc) WillBigInteger Convert toBigDecimal(rounding according to the context setting).
BigDecimal(char[] in) WillBigDecimal Character array representation is converted toBigDecimalAcceptance andBigDecimal(String)Constructs the same sequence of characters.
BigDecimal(char[] in, int offset, int len) WillBigDecimal Character array representation is converted toBigDecimalAcceptance andBigDecimal(String) Constructs the same sequence of characters while allowing subarrays to be specified.
BigDecimal(char[] in, int offset, int len, MathContext mc) WillBigDecimal Character array representation is converted toBigDecimalAcceptance andBigDecimal(String)Constructs a sequence of characters of the same type, allowing both subarrays to be specified and rounded according to context settings.
BigDecimal(char[] in, MathContext mc) WillBigDecimal Character array representation is converted toBigDecimalAcceptance andBigDecimal(String)A sequence of characters with the same constructor (rounded according to the context settings).
BigDecimal(double val) Willdouble Convert toBigDecimalThe latter isdouble The exact decimal representation of the binary floating point value.
BigDecimal(double val, MathContext mc) Willdouble Convert toBigDecimal(rounding according to the context setting).
BigDecimal(int val) Willint Convert toBigDecimal
BigDecimal(int val, MathContext mc) Willint Convert toBigDecimal(rounding according to the context setting).
BigDecimal(long val) Willlong Convert toBigDecimal
BigDecimal(long val, MathContext mc) Willlong Convert toBigDecimal(rounding according to the context setting).
BigDecimal(String val) WillBigDecimal The string representation is converted toBigDecimal
BigDecimal(String val, MathContext mc) WillBigDecimal The string representation is converted toBigDecimalAcceptance andBigDecimal(String)A string with the same constructor (rounded by context setting).

Method summary

Return value type Method name and parameter list Interpretation
BigDecimal abs() ReturnBigDecimal, its value is thisBigDecimal Absolute value, the scale isthis.scale()
BigDecimal abs(MathContext mc) Return its value to thisBigDecimal Absolute valueBigDecimal(rounding according to the context setting).
BigDecimal add(BigDecimal augend) Return oneBigDecimal, the value is(this + augend), whose scale ismax(this.scale(), augend.scale())
BigDecimal add(BigDecimal augend, MathContext mc) Return its value(this + augend) of BigDecimal(rounding according to the context setting).
byte byteValueExact() Do thisBigDecimal Convert tobyteTo check for missing information.
int compareTo(BigDecimal val) Do thisBigDecimal With the specifiedBigDecimal Comparison.
BigDecimal divide(BigDecimal divisor) Return oneBigDecimal, the value is(this / divisor), its preferred scale is(this.scale() - divisor.scale())If the exact quotient cannot be represented (because it has an infinite decimal extension), then throwArithmeticException
BigDecimal divide(BigDecimal divisor, int roundingMode) Return oneBigDecimal, the value is(this / divisor), whose scale isthis.scale()
BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) Return oneBigDecimal, the value is(this / divisor), whose scale is the specified scale.
BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) Return oneBigDecimal, the value is(this / divisor), whose scale is the specified scale.
BigDecimal divide(BigDecimal divisor, MathContext mc) Return its value(this / divisor) of BigDecimal(rounding according to the context setting).
BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) Return oneBigDecimal, the value is(this / divisor), whose scale isthis.scale()
BigDecimal[] divideAndRemainder(BigDecimal divisor) Returns a two-elementBigDecimal Array containing the arraydivideToIntegralValue The result, followed by the calculation of the two operandsremainder
BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) Returns a two-elementBigDecimal Array containing the arraydivideToIntegralValue Result, followed by rounding the two operands based on the context settingremainder the result of.
BigDecimal divideToIntegralValue(BigDecimal divisor) ReturnBigDecimal, whose value is rounded down to the quotient(this / divisor) The integer part.
BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) ReturnBigDecimal, the value is(this / divisor) The integer part.
double doubleValue() Do thisBigDecimal Convert todouble
boolean equals(Object x) Compare thisBigDecimal With the specifiedObject Equality.
float floatValue() Do thisBigDecimal Convert tofloat
int hashCode() Return thisBigDecimal Hash code.
int intValue() Do thisBigDecimal Convert toint
int intValueExact() Do thisBigDecimal Convert tointTo check for missing information.
long longValue() Do thisBigDecimal Convert tolong
long longValueExact() Do thisBigDecimal Convert tolongTo check for missing information.
BigDecimal max(BigDecimal val) Return thisBigDecimal with val The maximum value.
BigDecimal min(BigDecimal val):feet: Return thisBigDecimal with val The minimum value.
BigDecimal movePointLeft(int n) Return oneBigDecimal, which is equivalent to moving the decimal point of the value to the leftn Bit.
BigDecimal movePointRight(int n) Return oneBigDecimal, which is equivalent to moving the decimal point of the value to the rightn Bit.
BigDecimal multiply(BigDecimal multiplicand) Return oneBigDecimal, the value is(this × multiplicand), whose scale is(this.scale() + multiplicand.scale())
BigDecimal multiply(BigDecimal multiplicand, MathContext mc) Return its value(this × multiplicand) of BigDecimal(rounding according to the context setting).
BigDecimal negate() ReturnBigDecimal, the value is(-this), whose scale isthis.scale()
BigDecimal negate(MathContext mc) Return its value(-this) of BigDecimal(rounding according to the context setting).
BigDecimal plus() ReturnBigDecimal, the value is(+this), whose scale isthis.scale()
BigDecimal plus(MathContext mc) Return its value(+this) of BigDecimal(rounding according to the context setting).
BigDecimal pow(int n) Return its value(thisn) of BigDecimal, the power is calculated accurately to have infinite precision.
BigDecimal pow(int n, MathContext mc) Return its value(thisn) of BigDecimal
int precision() Return thisBigDecimal Precision.
BigDecimal remainder(BigDecimal divisor) Return its value(this % divisor) of BigDecimal
BigDecimal remainder(BigDecimal divisor, MathContext mc) Return its value(this % divisor) of BigDecimal(rounding according to the context setting).
BigDecimal round(MathContext mc) Return according toMathContext Set after roundingBigDecimal
int scale() Return thisBigDecimal The scale.
BigDecimal scaleByPowerOfTen(int n) Return its value equal to (this 10n) of BigDecimal.
BigDecimal setScale(int newScale) Return oneBigDecimal, whose scale is the specified value, and its value is numerically equal to thisBigDecimal Value.
BigDecimal setScale(int newScale, int roundingMode) Return oneBigDecimal, whose scale is the specified value, and its unscaled value passes thisBigDecimal The unscaled value is multiplied by or divided by the appropriate power of ten to determine its total value.
BigDecimal setScale(int newScale, RoundingMode roundingMode) ReturnBigDecimal, whose scale is the specified value, and its unscaled value passes thisBigDecimal The unscaled value is multiplied by or divided by the appropriate power of ten to determine its total value.
short shortValueExact() Do thisBigDecimal Convert toshortTo check for missing information.
int signum() Return thisBigDecimal The sign function.
BigDecimal stripTrailingZeros() Returns a number equal to this decimal, but removes all trailing zeros from this representationBigDecimal
BigDecimal subtract(BigDecimal subtrahend) Return oneBigDecimal, the value is(this - subtrahend), whose scale ismax(this.scale(), subtrahend.scale())
BigDecimal subtract(BigDecimal subtrahend, MathContext mc) Return its value(this - subtrahend) of BigDecimal(rounding according to the context setting).
BigInteger toBigInteger() Do thisBigDecimal Convert toBigInteger
BigInteger toBigIntegerExact() Do thisBigDecimal Convert toBigIntegerTo check for missing information.
String toEngineeringString() Return thisBigDecimal The string representation, when an index is required, uses the engineering notation.
String toPlainString() Return this without an exponent fieldBigDecimal a string representation.
String toString() Return thisBigDecimal A string representation, if an index is required, use scientific notation.
BigDecimal ulp() Return thisBigDecimal The size of the ulp (the last bit of the unit).
BigInteger unscaledValue() Return its value to thisBigDecimal Unscaled valueBigInteger
static BigDecimal valueOf(double val) UseDouble.toString(double)Method provideddouble The canonical string representation willdouble Convert toBigDecimal
static BigDecimal valueOf(long val) Willlong Convert values ​​to zero scaleBigDecimal
static BigDecimal valueOf(long unscaledVal, int scale) Willlong Unscaled value andint Scale converted toBigDecimal

Several examples

Large number A+B

Code

import java.math.BigInteger;
import java.util.Scanner;

class BigNumberTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        BigInteger bI1 = sc.nextBigInteger(),
                bI2 = sc.nextBigInteger(),
                bI3 = bI1.add(bI2);
        System.out.println(bI3);
        sc.close();
    }
}

Compare cpp large number template

#include<iostream> 
#include<string> 
#include<iomanip> 
#include<algorithm> 
using namespace std; 

#define MAXN 9999
#define MAXSIZE 10
#define DLEN 4

class BigNum
{ 
private: 
	int a[500];    / / Can control the number of digits 
	int len;       //large length
public: 
	BigNum(){ len = 1;memset(a,0,sizeof(a)); }   //Constructor
	BigNum(const int);       / / Convert a variable of type int to a large number
	BigNum(const char*);     / / Convert a string type variable into a large number
	BigNum(const BigNum &);  / / copy constructor
	BigNum &operator=(const BigNum &);   / / Overload assignment operator, assignment between large numbers

	friend istream& operator>>(istream&,  BigNum&);   // overloaded input operator
	friend ostream& operator<<(ostream&,  BigNum&);   // overloaded output operator

	BigNum operator+(const BigNum &) const;   / / Overloading the addition operator, the addition of two large numbers 
	BigNum operator-(const BigNum &) const;   // overloaded subtraction operator, subtraction between two large numbers 
	BigNum operator*(const BigNum &) const;   //Overload multiplication operator, multiplication between two large numbers 
	BigNum operator/(const int   &) const;    / / Overload division operator, large number is divided by an integer

	BigNum operator^(const int  &) const;    //The n-th power of the big number
	int    operator%(const int  &) const;    / / Large number of modulo operations on a variable of type int    
	bool   operator>(const BigNum & T)const;   / / Large size and another large size comparison
	bool   operator>(const int & t)const;      / / Large size and the size of a variable of type int comparison

	void print();       / / Output large number
}; 
BigNum::BigNum(const int b)     / / Convert a variable of type int to a large number
{ 
	int c,d = b;
	len = 0;
	memset(a,0,sizeof(a));
	while(d > MAXN)
	{
		c = d - (d / (MAXN + 1)) * (MAXN + 1); 
		d = d / (MAXN + 1);
		a[len++] = c;
	}
	a[len++] = d;
}
BigNum::BigNum(const char*s)     / / Convert a string type variable into a large number
{
	int t,k,index,l,i;
	memset(a,0,sizeof(a));
	l=strlen(s);   
	len=l/DLEN;
	if(l%DLEN)
		len++;
	index=0;
	for(i=l-1;i>=0;i-=DLEN)
	{
		t=0;
		k=i-DLEN+1;
		if(k<0)
			k=0;
		for(int j=k;j<=i;j++)
			t=t*10+s[j]-'0';
		a[index++]=t;
	}
}
BigNum::BigNum(const BigNum & T) : len(T.len)  / / copy constructor
{ 
	int i; 
	memset(a,0,sizeof(a)); 
	for(i = 0 ; i < len ; i++)
		a[i] = T.a[i]; 
} 
BigNum & BigNum::operator=(const BigNum & n)   / / Overload assignment operator, assignment between large numbers
{
	int i;
	len = n.len;
	memset(a,0,sizeof(a)); 
	for(i = 0 ; i < len ; i++) 
		a[i] = n.a[i]; 
	return *this; 
}
istream& operator>>(istream & in,  BigNum & b)   // overloaded input operator
{
	char ch[MAXSIZE*4];
	int i = -1;
	in>>ch;
	int l=strlen(ch);
	int count=0,sum=0;
	for(i=l-1;i>=0;)
	{
		sum = 0;
		int t=1;
		for(int j=0;j<4&&i>=0;j++,i--,t*=10)
		{
			sum+=(ch[i]-'0')*t;
		}
		b.a[count]=sum;
		count++;
	}
	b.len =count++;
	return in;

}
ostream& operator<<(ostream& out,  BigNum& b)   // overloaded output operator
{
	int i;  
	cout << b.a[b.len - 1]; 
	for(i = b.len - 2 ; i >= 0 ; i--)
	{ 
		cout.width(DLEN); 
		cout.fill('0'); 
		cout << b.a[i]; 
	} 
	return out;
}

BigNum BigNum::operator+(const BigNum & T) const   //Addition between two large numbers
{
	BigNum t(*this);
	int i,big;      //digits   
	big = T.len > len ? T.len : len; 
	for(i = 0 ; i < big ; i++) 
	{ 
		t.a[i] +=T.a[i]; 
		if(t.a[i] > MAXN) 
		{ 
			t.a[i + 1]++; 
			t.a[i] -=MAXN+1; 
		} 
	} 
	if(t.a[big] != 0)
		t.len = big + 1; 
	else
		t.len = big;   
	return t;
}
BigNum BigNum::operator-(const BigNum & T) const   //The subtraction between two large numbers 
{  
	int i,j,big;
	bool flag;
	BigNum t1,t2;
	if(*this>T)
	{
		t1=*this;
		t2=T;
		flag=0;
	}
	else
	{
		t1=T;
		t2=*this;
		flag=1;
	}
	big=t1.len;
	for(i = 0 ; i < big ; i++)
	{
		if(t1.a[i] < t2.a[i])
		{ 
			j = i + 1; 
			while(t1.a[j] == 0)
				j++; 
			t1.a[j--]--; 
			while(j > i)
				t1.a[j--] += MAXN;
			t1.a[i] += MAXN + 1 - t2.a[i]; 
		} 
		else
			t1.a[i] -= t2.a[i];
	}
	t1.len = big;
	while(t1.a[t1.len - 1] == 0 && t1.len > 1)
	{
		t1.len--; 
		big--;
	}
	if(flag)
		t1.a[big-1]=0-t1.a[big-1];
	return t1; 
} 

BigNum BigNum::operator*(const BigNum & T) const   //Multiplication between two large numbers 
{ 
	BigNum ret; 
	int i,j,up; 
	int temp,temp1;   
	for(i = 0 ; i < len ; i++)
	{ 
		up = 0; 
		for(j = 0 ; j < T.len ; j++)
		{ 
			temp = a[i] * T.a[j] + ret.a[i + j] + up; 
			if(temp > MAXN)
			{ 
				temp1 = temp - temp / (MAXN + 1) * (MAXN + 1); 
				up = temp / (MAXN + 1); 
				ret.a[i + j] = temp1; 
			} 
			else
			{ 
				up = 0; 
				ret.a[i + j] = temp; 
			} 
		} 
		if(up != 0) 
			ret.a[i + j] = up; 
	} 
	ret.len = i + j; 
	while(ret.a[ret.len - 1] == 0 && ret.len > 1)
		ret.len--; 
	return ret; 
} 
BigNum BigNum::operator/(const int & b) const   / / Large numbers are divided by an integer
{ 
	BigNum ret; 
	int i,down = 0;   
	for(i = len - 1 ; i >= 0 ; i--)
	{ 
		ret.a[i] = (a[i] + down * (MAXN + 1)) / b; 
		down = a[i] + down * (MAXN + 1) - ret.a[i] * b; 
	} 
	ret.len = len; 
	while(ret.a[ret.len - 1] == 0 && ret.len > 1)
		ret.len--; 
	return ret; 
}
int BigNum::operator %(const int & b) const    / / Large number of modulo operations on a variable of type int    
{
	int i,d=0;
	for (i = len-1; i>=0; i--)
	{
		d = ((d * (MAXN+1))% b + a[i])% b;  
	}
	return d;
}
BigNum BigNum::operator^(const int & n) const    //The n-th power of the big number
{
	BigNum t,ret(1);
	int i;
	if(n<0)
		exit(-1);
	if(n==0)
		return 1;
	if(n==1)
		return *this;
	int m=n;
	while(m>1)
	{
		t=*this;
		for( i=1;i<<1<=m;i<<=1)
		{
			t=t*t;
		}
		m-=i;
		ret=ret*t;
		if(m==1)
			ret=ret*(*this);
	}
	return ret;
}
bool BigNum::operator>(const BigNum & T) const   / / Large size and another large size comparison
{ 
	int ln; 
	if(len > T.len)
		return true; 
	else if(len == T.len)
	{ 
		ln = len - 1; 
		while(a[ln] == T.a[ln] && ln >= 0)
			ln--; 
		if(ln >= 0 && a[ln] > T.a[ln])
			return true; 
		else
			return false; 
	} 
	else
		return false; 
}
bool BigNum::operator >(const int & t) const    / / Large size and the size of a variable of type int comparison
{
	BigNum b(t);
	return *this>b;
}

void BigNum::print()    / / Output large number
{ 
	int i;   
	cout << a[len - 1]; 
	for(i = len - 2 ; i >= 0 ; i--)
	{ 
		cout.width(DLEN); 
		cout.fill('0'); 
		cout << a[i]; 
	} 
	cout << endl;
}

Java encapsulates the large number of classes in the Biginteger package, which reduces the difficulty of the programmer's work. It is obvious that the language founders consider the importance of thoughtfulness.


ZCMU1179: ab-ba

answer

import java.math.BigInteger;
import java.util.Scanner;

import static java.lang.System.*;

class BigNumberTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        BigInteger bI1 = sc.nextBigInteger(),
                bI2 = sc.nextBigInteger(),
                ans = bI1.pow(bI2.intValue()).subtract(bI2.pow(bI1.intValue()));
        out.println(ans);
        sc.close();
    }
}

A+B

Description of the topic

Given two integers A and B, the representation is: starting with a single digit, each three digits are separated by a comma ",". Now calculate the result of A+B and output it in the normal form.

Enter a description:

The input contains multiple sets of data, one for each group of data, consisting of two integers A and B (-10^9 < A, B < 10^9).

Output description:

Please calculate the result of A+B and output it in the normal form, one data per group.

Example 1

Input

-234,567,890 123,456,789
1,234 2,345,678

Output

-111111101
2346912

Topic link

answer

import java.math.BigInteger;
import java.util.Scanner;

import static java.lang.System.*;

class BigNumberTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String tmp;
        BigInteger bI1, bI2, ans;
        while (sc.hasNext()) {
            tmp = sc.nextLine();
            String[] str = tmp.split(" ", 2);
            str[0] = str[0].replaceAll(",", "");
            bI1 = new BigInteger(str[0]);
            str[1] = str[1].replaceAll(",", "");
            bI2 = new BigInteger(str[1]);
            ans = bI1.add(bI2);
            out.println(ans);
        }
        sc.close();
    }
}


Considerations when using Java Answers

  • The class name of the submitted code master method must be public class Main{}, otherwise the judger does not recognize

  • Try to use IDE or editor with code highlighting and automatic formatting code. No students can choose to compile and test online on Cloud IDE.

    download link

    Java IDE: Intellij Idea(It is strongly recommended that JetBrains have a family bucket, a bucket in hand, compile without worry),Eclipse

    editor:Visual Studio Code, sublime text 3

    Cloud IDE:www.ideone.com, www.compilejava.net

  • The best teacher of the programmer is always the document. Go online and look for the Java API to find more fun secrets

Intelligent Recommendation

java high-precision calculation

This is only for multiplication...

High precision value in Java

Large value in Java In Java, if the basic integer Integer and floating point Double Double have not satisfied, then you can usejava.mathTwo classes in the package:BigIntegerwithBigDecimal. These two c...

[Java] high precision

Java writes high precision is so convenient, other or C ++....

Java high precision operation

There are two classes in Java to handle high-precision calculations. Treat an integerBigIntegerAnd processing decimalBigDecimal Biginteger can only be used in integers Construction method Adding add (...

Summary of handling high concurrency problems

High concurrency processing can roughly be considered from ten aspects: 1. Start from the most basic place, optimize the code we write, and briefly discuss unnecessary waste of resources. 2. HTML stat...

More Recommendation

Large number problems in high-precision calculations

Large number problems in high-precision calculations Preface¶ storage¶ Arithmetic¶ addition¶ Subtraction¶ multiplication¶ High precision-single precision¶ High preci...

[ACM Algorithm]-Mathematical Problems-High Precision Integer

first question: Ideas: For high-precision integer problems, it is actually very simple, which is equivalent to a template function. As long as you memorize it, there is no problem. The specific idea i...

C language notes: high-precision calculation problems

Article Directory Brief description of big data types in C language High precision addition High-precision multiplication Brief description of big data types in C language We know that directly using ...

Basic algorithm problems-high precision addition

High precision addition a+b=c Since both a and b are relatively large, they cannot be stored directly using standard data types in the language. For this kind of problem, generally use an array to dea...

Java implementation of high-precision examples

Title description Given an integer a, ask if it can be divided by 3, note that a may be very large Input The input includes multiple test instances, each test case occupies one line, each line is an i...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top