美文网首页
Java大数运算

Java大数运算

作者: StilllFantasy | 来源:发表于2019-02-25 21:01 被阅读0次

关于大数运算,c++选手需要自己编写高精度算法,而Java则自带大整数类。这篇文章简单记录一下,关于Java大数运算的写法

必要:

import java.math.BigInteger;

定义一个大数:

BigInteger num = new BigInteger;

大数数组定义:

BigInteger [] num = new BigInteger [100];
BigInteger [][] num = new BigInteger [10][10];

给它赋值:

num = BigInteger.valueof(X);
BigInteger num = new BigInteger("123");

基本运算:

BigInteger num1 = new BigInteger("123");
BigInteger num2 = new BigInteger("456");
  • 加法
    num1 = num1.add(num2);
  • 减法
    num1 = num1.subtract(num2);
  • 乘法
    num1 = num1.multiply(num2);
  • 除法
    num1 = num1.divide(num2);
  • 取模
    num1 = num1.remainder(num2);

小结

Java大数运算可能刚开始会感觉比较麻烦,用习惯就好,还有其它的一些操作,比如比较两个数(compare),取绝对值(abs),甚至连gcd都直接给封装好了,所以还是挺方便的,以后再也不头疼写c++大数运算了

相关文章

网友评论

      本文标题:Java大数运算

      本文链接:https://www.haomeiwen.com/subject/ffrnyqtx.html