基础算法 —— 高精度计算 —— Java 大数类
生活随笔
收集整理的這篇文章主要介紹了
基础算法 —— 高精度计算 —— Java 大数类
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
【概述】
在 C++ 中數(shù)據(jù)類型的長度最多能到 64 位,一旦超出這個位數(shù),就要用數(shù)組進行模擬計算,即高精度算法
而在 Java 中有兩個類:BigInteger、BigDecimal 分別表示大整數(shù)類和大浮點數(shù)類,其理論上能表示無限大的數(shù),只要計算機內(nèi)存足夠大。?
這兩個類都是 Number 類的子類,但存放在 java.math.* 包中,因此每次使用必須在開頭處引用該包。
【常量】
BigInteger 的 ONE、ZERO、TEN 分別代表 1、0、10
BigInteger.ZERO //大整數(shù)0 BigInteger.ONE //大整數(shù)1 BigInteger.TEN //大整數(shù)10而在 BigDecimal 中除了以上三個常量外還有8個關(guān)于舍入的常量:ROUND_UP、ROUND_DOWN、ROUND_CEILING、ROUND_FLOOR、ROUND_HALF_UP、ROUND_HALF_DOWN、ROUND_HALF_EVEN、ROUND_UNNECESSARY。
【聲明賦值】
基本類型的定義:
BigInteger name?= new BigInteger(String)?;//參數(shù)是字符串? BigInteger name?= BigInteger.valueOf(123); //參數(shù)是 int、long BigDecimal name?= new BigDecimal(String)?;//參數(shù)是字符串? BigDecimal name?= BigDecimal.valueOf(123.45); //參數(shù)是 float、double【輸入框架】
Scanner input = new Scanner(System.in); while(input.hasNext()){ BigInteger a;a = input.BigInteger();System.out.println(a); }【基本用法】
1.四則運算
BigInteger a = new BigInteger.valueOf(10); BigInteger b = new BigInteger.valueOf(10); BigInteger res new BigInteger(); res=a.add(b); //加法 res=a.subtract(b); //減法 res=a.divide(b); //除法 res=a.multiply(b); //乘法2.比較大小
BigInteger a = new BigInteger.valueOf(10); BigInteger b = new BigInteger.valueOf(10); a.equals(b); //如果a、b相等返回true否則返回false a.comareTo(b); //a小于b返回-1,等于返回0,大于返回13.常用方法
BigInteger a = new BigInteger.valueOf(10); BigInteger b = new BigInteger.valueOf(15); BigInteger mod = new BigInteger.valueOf(10007); BigInteger res=new BigInteger(); res=a.mod(mod); //求余 res=a.gcd(b); //求最大公約數(shù) res=a.max(b); //求最大值 res=a.min(b); //求最小值 res=a.modPow(b,mod); //求(a^b)%mod?
新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎!定制產(chǎn)品紅包拿不停!總結(jié)
以上是生活随笔為你收集整理的基础算法 —— 高精度计算 —— Java 大数类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 图论 —— 生成树 —— 生成树计数
- 下一篇: 2019 年“浪潮杯”第十届山东省 AC