首页 > 代码库 > java大数专题

java大数专题

HDU 1002 大数加减

import java.util.*;
import java.math.*;
import java.io.*;

public class Main 
{
	public static void main(String args[])
	{
		Scanner cin = new Scanner(System.in);
		int t=cin.nextInt();
		for(int i=1;i<=t;i++)
		{
			BigInteger a=cin.nextBigInteger();
			BigInteger b=cin.nextBigInteger();
			BigInteger c=a.add(b);
			System.out.println("Case "+i+":");
			System.out.println(a+" + "+b+" = "+c);
			if(i!=t) System.out.println("");
		}
	}
}


HDU 1042 大数相乘

import java.util.*;
import java.math.*;
import java.io.*;

public class Main 
{
	public static void main(String args[])
	{
		Scanner cin = new Scanner(System.in);
		BigInteger n,i,sum;
		while(cin.hasNextBigInteger())
		{
			n=cin.nextBigInteger();
			sum=BigInteger.ONE;
			i=BigInteger.valueOf(2);
			while(i.compareTo(n)<=0)
			{
				sum=sum.multiply(i);
				i=i.add(BigInteger.ONE);
			}
			System.out.println(sum);
		}
	}
}

HDU 1047 大数相乘

import java.util.*;
import java.math.*;
import java.io.*;

public class Main 
{
	public static void main(String args[])
	{
		Scanner cin = new Scanner(System.in);
		while(cin.hasNextBigInteger())
		{
			int t=cin.nextInt();
			while(t-->0)
			{
				boolean flag=true;
				BigInteger sum=BigInteger.ZERO;
				while(flag)
				{
					BigInteger a=cin.nextBigInteger();
					if(a.compareTo(BigInteger.ZERO)==0) flag=false;
					else sum=sum.add(a);
				}
				System.out.println(sum);
				if(t!=0) System.out.println("");
			}
		}
	}
}

HDU 1063 大数幂与大数转换成字符串的处理

import java.util.*;
import java.math.*;
import java.io.*;

public class Main 
{
	public static void main(String args[])
	{
		Scanner cin = new Scanner(System.in);
		while(cin.hasNextBigDecimal())
		{
			BigDecimal p=cin.nextBigDecimal();
			int n=cin.nextInt();
			p=p.pow(n);
			p=p.stripTrailingZeros(); //去掉后倒0
			String s=p.toPlainString(); //不让其变成科学计数法的表示法,变成一般的小数表示
			if(s.startsWith("0.")) s=s.substring(1); //与前导的字符串比较
			System.out.println(s);
		}
	}
}