大数(java)

•  大数加法

 给出2个大整数A,B,计算A+B的结果

   Input

    第1行:大数A 第2行:大数B (A,B的长度 <= 10000 需注意:A B有可能为负数)

       Output

输出A + B

 

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

public class Main {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);    
        /*    大数初始化
             BigInteger c = BigInteger.valueOf(1);
            System.out.println(c);
        */
        while(in.hasNext()) {
            BigInteger a=in.nextBigInteger();
            BigInteger b=in.nextBigInteger();
            System.out.println(a.add(b));
        }
    }
    
}

•  其他

///减法
System.out.println(a.subtract(b));
///乘法
System.out.println(a.multiply(b));
///相除取整
System.out.println(a.divide(b));
///取余
System.out.println(a.remainder(b));
/// a^b     a.pow(b)
///最大公约数   gcd()
///绝对值       abs()
///取反数       negate()
///取模     a.mod(b)

 

•  大数阶乘

  c++ 参考 https://blog.csdn.net/qq_33850438/article/details/50631619

  斯特林近似 n! = sqrt((2 * n * PI) * (n / e ) ^ n) 

 

#define PI acos(-1.0)  ///圆周率
#define e exp(1)  ///自然常数

 

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

public class Main {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        while(in.hasNext()) {
            BigInteger N=in.nextBigInteger();
            BigInteger sum = BigInteger.valueOf(1);
            BigInteger one = BigInteger.valueOf(1);
            for(BigInteger i=BigInteger.valueOf(2);i.compareTo(N)<=0;i=i.add(one)) {
                sum=sum.multiply(i);
            }
            System.out.println(sum);
        }
    }
    
}

 

•  未完待续

posted @ 2018-06-06 19:22  ___292  阅读(122)  评论(0编辑  收藏  举报