java 大数类使用及案例

来源:互联网 发布:unity3d speedtree 编辑:程序博客网 时间:2024/05/22 04:40

16年9月22日,感觉是时候复习算法,重新进军进军竞赛大军了。所有将会每天进行算法训练,但是不会放弃java软件设计和前端学习。
SO

正题来了,将昨天的大数类整理如下:

  1. 定义大数变量:BigInteger x, BigInteger y;
  2. 大数相加:x.add(y)
  3. 大数相减:x.subtract(y)
  4. 大数相乘:x.multiply(y)
  5. 大数相除:x.divide(y)
  6. 大数模运算:x.remainder(y)
  7. 大数与大数之间赋值:x = y;
  8. 大数与非大数之间赋值:x = BigIntteger.valueOf(int val)
  9. 大数之间大小比较:x.compareTo(y)

更多函数请参考API

Example:

nyoj 45

import java.math.BigInteger;import java.util.Scanner;public class Main {    public static void main(String[] args) {        BigInteger res;        int n, k;        Scanner in = new Scanner(System.in);        n = in.nextInt();        for (int i = 0; i < n; i++)        {            res = BigInteger.valueOf(2);            k  = in.nextInt();            res = res.pow(2*k);            res = res.subtract(BigInteger.ONE);            res = res.divide(BigInteger.valueOf(3));            System.out.println(res);        }    }}

nyoj 28

import java.math.BigInteger;import java.util.Scanner;public class Main {    public static void main(String[] args) {        // TODO Auto-generated method stub        BigInteger x, y;        int n;        Scanner in = new Scanner(System.in);        n = in.nextInt();        long start = System.currentTimeMillis();        x = BigInteger.valueOf(1);        for(int i = 1; i <= n; i++)        {            y =  BigInteger.valueOf(i);            x = x.multiply(y);        }        System.out.println(x);        long end = System.currentTimeMillis();//      Float time = (float) ((end-start)/1000);        long runTime = end - start;        System.out.println(runTime);    }}

nyoj 73

import java.math.BigInteger;import java.util.Scanner;public class Main {    public static void main(String[] args) {        BigInteger x, y;        Scanner in = new Scanner(System.in);        x = in.nextBigInteger();        y = in.nextBigInteger();        while(!x.equals(BigInteger.ZERO) && !y.equals(BigInteger.ZERO))        {            if(x.compareTo(y) > 0) System.out.println("a>b");            else if(x.compareTo(y) < 0) System.out.println("a<b");            else System.out.println("a==b");            x = in.nextBigInteger();            y = in.nextBigInteger();        }    }}

nyoj 103

import java.math.BigInteger;import java.util.Scanner;public class Main {    public static void main(String[] args) {        int t;        BigInteger x, y, res;        Scanner in = new Scanner(System.in);        t = in.nextInt();        for(int i = 1; i <= t; i++)        {            x = in.nextBigInteger();            y = in.nextBigInteger();            res = x.add(y);            System.out.println("Case "+i+":");            System.out.println(x + " + " + y + " = " +res);        }    }}
1 0