1. 程式人生 > >JAVA大數模板

JAVA大數模板

 

大數取餘

BigInteger bi = new BigInteger(99999999999999999999);
int i = bi.remainder(nwe BigInteger(10)).intValue();

JAVA模板 大整數模板 高精度

儲存為main.java (class名相同)

import java.io.*;
import java.util.*;
import java.math.*;
public class main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		BigInteger mod = BigInteger.valueOf(1);
		for(int i = 1; i <= 100; i++)
			mod = mod.multiply(BigInteger.valueOf(10));
		while(in.hasNext())
		{
			int n = in.nextInt();
			BigInteger ans = BigInteger.valueOf(1);
			BigInteger ret = BigInteger.valueOf(1);
			for(int i = 1; i+i <= n; i++)
			{
				ans = ans.multiply(BigInteger.valueOf(n-2*i+2));
				ans = ans.multiply(BigInteger.valueOf(n-2*i+1));
				ans = ans.divide(BigInteger.valueOf(i));
				ans = ans.divide(BigInteger.valueOf(i+1));
				ret = ret.add(ans);
			}
			ret = ret.mod(mod);
			System.out.println(ret);
		}
	}
}

多維陣列初始化

BigInteger f[] = new BigInteger[110];  
        BigInteger c[][] = new BigInteger[110][110];  
        for ( int i = 0 ; i <= 100 ; i++ )   
            for ( int j = 0 ; j <= 100 ; j++ ) c[i][j] = BigInteger.valueOf(0);  //別忘了初始化

檔案輸入輸出

//H
import java.io.*;
import java.util.*;
import java.math.*;
public class main {
	public static void main(String[] args) throws FileNotFoundException {
		//Scanner in = new Scanner(new File("trains.in"));
        //PrintWriter out = new PrintWriter(new File("trains.out"));
        FileInputStream cin = new FileInputStream("trains.in");
        FileOutputStream cout = new FileOutputStream("trains.out");
        Scanner in = new Scanner(cin);
        PrintStream out = new PrintStream(cout);

        BigInteger f[] = new BigInteger[110];
        BigInteger c[][] = new BigInteger[110][110];
        for ( int i = 0 ; i <= 100 ; i++ ) 
            for ( int j = 0 ; j <= 100 ; j++ ) c[i][j] = BigInteger.valueOf(0);
        c[0][0]=BigInteger.valueOf(1);
		for(int i = 1; i <= 100; i++)
        {
            c[i][0]=BigInteger.valueOf(1);
            for (int j=1; j<=i; j++)
            {
                c[i][j] = c[i-1][j-1].add(c[i-1][j]);
            }
        }
        f[2]=BigInteger.valueOf(1);
        for (int i=3; i<=100; i++)
        {
            f[i]=BigInteger.valueOf(2).pow(i*(i-1)/2);
            for (int j=2; j<=i-1; j++)
                f[i]=f[i].subtract(f[j].multiply(c[i][j]));
            f[i]=f[i].subtract(BigInteger.valueOf(1));
        }
		while(in.hasNext()) 
		{
			int n = in.nextInt(); //input
            out.println(f[n]);
		}
		in.close();
        out.close(); //close
	}
}