JAVA大数处理(BigInteger,BigDecimal)

Java中的大数处理:BigInteger与BigDecimal深度解析 在 Java 中,intlongfloat和double等基本数值类型受限于固定位数,无法满足高精度或超大数值的计算需求。例如,long最大仅支持约 9×10¹⁸,而金融计算中常需精确到小数点后多位,避免舍入误差累积;密码学(如 RSA 算法)则涉及数百位的整数运算。为此,Java 提供了java.math包中的 BigInteger(任意精度整数)和 BigDecimal(任意精度十进制数)。需要注意的是,大数对象是不可变的,且所有运算必须通过方法调用(如add()multiply() 阅读详情

JAVA大数处理(BigInteger,BigDecimal)  

转自:http://hi.baidu.com/dolphin0520/blog/item/a0c88b1eb8ac86c4a786699e.html

      在用C或者C++处理大数时感觉非常麻烦,但是在JAVA中有两个类BigInteger和BigDecimal分别表示大整数类和大浮点数类,至于两个类的对象能表示最大范围不清楚,理论上能够表示无线大的数,只要计算机内存足够大。

这两个类都在java.math.*包中,因此每次必须在开头处引用该包。

Ⅰ基本函数:

1.valueOf(parament); 将参数转换为制定的类型

  比如 int a=3;

       BigInteger b=BigInteger.valueOf(a);

     则b=3;

         String s=”12345”;

       BigInteger c=BigInteger.valueOf(s);

      则c=12345;

2.add(); 大整数相加

   BigInteger a=new BigInteger(“23”);

   BigInteger b=new BigInteger(“34”);

a.      add(b);

3.subtract(); 相减

4.multiply(); 相乘

5.divide();    相除取整

6.remainder();取余

7.pow();   a.pow(b)=a^b

8.gcd();   最大公约数

9.abs(); 绝对值

10.negate();取反数

11.mod(); a.mod(b)=a%b=a.remainder(b);

12.max(); min();

13.punlic int comareTo();

14.boolean equals(); 是否相等

15.BigInteger构造函数:

  一般用到以下两种:

   BigInteger(String val);

将指定字符串转换为十进制表示形式;

   BigInteger(String val,int radix);

将指定基数的BigInteger的字符串表示形式转换为BigInteger

Ⅱ.基本常量:

   A=BigInteger.ONE    1

B=BigInteger.TEN    10

C=BigInteger.ZERO   0

Ⅲ.基本操作

1.   读入:

用Scanner类定义对象进行控制台读入,Scanner类在java.util.*包中

Scanner cin=new Scanner(System.in);// 读入

while(cin.hasNext())   //等同于!=EOF

{

   int n;

   BigInteger m;

   n=cin.nextInt(); //读入一个int;

   m=cin.BigInteger();//读入一个BigInteger;

System.out.print(m.toString());

}

Ⅳ.运用

四则预算:

import java.util.Scanner;
import java.math.*;
import java.text.*;

public class Main 
{
public static void main(String args[])
{
   Scanner cin = new Scanner ( System.in );
   BigInteger a,b;
   int c;
   char op;
   String s;
  
   while( cin.hasNext() )
   {
    a = cin.nextBigInteger();
    s = cin.next();
    op = s.charAt(0);
    if( op == '+')
    {
     b = cin.nextBigInteger();
     System.out.println(a.add(b));
    }
    else if( op == '-')
    {
     b = cin.nextBigInteger();
     System.out.println(a.subtract(b));
    }
    else if( op == '*')
    {
     b = cin.nextBigInteger();
     System.out.println(a.multiply(b));
    }
    else
    {
     BigDecimal a1,b1,eps;
     String s1,s2,temp;
     s1 = a.toString();
       a1 = new BigDecimal(s1);
     b = cin.nextBigInteger();
     s2 = b.toString();
     b1 = new BigDecimal(s2);
     c = cin.nextInt();
     eps = a1.divide(b1,c,4);
     //System.out.println(a + " " + b + " " + c);
     //System.out.println(a1.doubleValue() + " " + b1.doubleValue() + " " + c);
     System.out.print( a.divide(b) + " " + a.mod(b) + " ");
     if( c != 0)
     {
      temp = "0.";
      for(int i = 0; i < c; i ++) temp += "0";
      DecimalFormat gd = new DecimalFormat(temp);
      System.out.println(gd.format(eps));
     }
     else System.out.println(eps);
    }
   }
   }
}


下面是关于大数处理的部分代码。
/**
 * @author zhangyong
 * 
 */
public class BigInt {

/**
 * @param args
 */
public static void main(String[] args) {
BigInt b = new BigInt();
b.add("999", "999");
}

public String add(String a, String b) {
//检查输入
if (!a.matches("\\d+") || !a.matches("\\d+")) {
return null;
}
final int BASE = 10;//10进制
int lenA = a.length();//加数的长度
int lenB = b.length();//被加数的长度
int maxLen, partialSum, carry = 0;//大数的长度,和,进位
maxLen = (lenA > lenB) ? lenA : lenB;
StringBuffer sum = new StringBuffer();
int temA, temB = 0;
for (int i = 0; i < maxLen; i++) {
if (i >= lenA) {
temA = 0;
} else {
temA = Integer.valueOf(a.charAt(lenA - i - 1) - 48);
}
if (i >= lenB) {
temB = 0;
} else {
temB = Integer.valueOf(b.charAt(lenB - i - 1) - 48);
}
partialSum = temA + temB + carry;
carry = partialSum / BASE;
sum.append(partialSum % BASE);
}
if (carry == 1)
sum.append(carry);
System.out.println(a + "+" + b + "=" + sum.reverse().toString());
return sum.reverse().toString();
}
}



另一个版本:
package test;
public class VeryBigNumAdd {

public static void main(String[] args) {
VeryBigNumAdd vbn = new VeryBigNumAdd();
String a = "123453243455535634535252345234677576252241234123523453664563634";
String b = "123453243455535634535252345234677576252241234123523453664563634";
String result = vbn.doAdd(a, b);
System.out.println("result:" + result);
}

String doAdd(String a, String b) {
String str = "";
int lenA = a.length();
int lenB = b.length();
int maxLen = (lenA > lenB) ? lenA : lenB;
int minLen = (lenA < lenB) ? lenA : lenB;
String strTmp = "";
for (int i = maxLen - minLen; i > 0; i--) {
strTmp += "0";
}
// 把长度调整到相同
if (maxLen == lenA) {
b = strTmp + b;
} else
a = strTmp + a;
int JW = 0;// 进位
for (int i = maxLen - 1; i >= 0; i--) {
int tempA = Integer.parseInt(String.valueOf(a.charAt(i)));
int tempB = Integer.parseInt(String.valueOf(b.charAt(i)));
int temp;
if (tempA + tempB + JW >= 10 && i != 0) {
temp = tempA + tempB + JW - 10;
JW = 1;
} else {
temp = tempA + tempB + JW;
JW = 0;
}
str = String.valueOf(temp) + str;
}
return str;
}
}

又一个版本:

import java.util.ArrayList;
import java.util.Collections;
public class VeryLongInt {

ArrayList digits;

// Postcondition: The VeryLongInt is empty.
public VeryLongInt() {
final int INITIAL_CAPACITY = 500;
digits = new ArrayList(INITIAL_CAPACITY);
} // default constructor

// Precondition: n >= 0.
// Postcondition: The VeryLongInt has been initialized from the
// not-very-long int n.
public VeryLongInt(int n) {
final int BASE = 10;
digits = new ArrayList();
do {
digits.add(new Integer(n % BASE));
n = n / BASE;
} // while
while (n > 0);
// digits is now in reverse order, so we reverse:
Collections.reverse(digits);

} // constructor

// Postcondition: The number of elements in the VeryLongInt has
// been returned.
public int size() {
return digits.size();
} // method size

// Precondition: The string s consists of a sequence of characters
// with non-digit characters ignored.
// There are no leading zeroes, except for 0
// itself, which has a single '0'.
// Postcondition: The VeryLongInt has been initialized from s.
public VeryLongInt(String s) {
final char LOWEST_DIGIT_CHAR = '0';
final char HIGHEST_DIGIT_CHAR = '9';
digits = new ArrayList(s.length());
char c;
int digit;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if ((LOWEST_DIGIT_CHAR <= c) && (c <= HIGHEST_DIGIT_CHAR)) {

digit = c - LOWEST_DIGIT_CHAR;
digits.add(new Integer(digit));
} // if a digit
} // for
} // constructor with string parameter

// Postcondition: The VeryLongInt has been returned as a string of digits.
public String toString() {
final String EMPTY_STRING = "";
String s = EMPTY_STRING;
for (int i = 0; i < digits.size(); i++)
s += digits.get(i);
return s;

} // method toString

// Postcondition: If i >= digits.size(), 0 has been returned; else
// the ith least significant digit in digits has
// been returned. The least significant digit is
// the 0th least significant digit.
private int least(int i) {
if (i >= digits.size())
return 0;
else
return ((Integer) (digits.get(digits.size() - i - 1))).intValue();
} // least

// Postcondition: The VeryLongInt has been incremented by otherVeryLong.
public void add(VeryLongInt otherVeryLong) {
final int BASE = 10;
int largerSize, partialSum, carry = 0;
VeryLongInt sum = new VeryLongInt();
if (digits.size() > otherVeryLong.digits.size())
largerSize = digits.size();
else
largerSize = otherVeryLong.digits.size();

for (int i = 0; i < largerSize; i++) {

partialSum = least(i) + otherVeryLong.least(i) + carry;
carry = partialSum / BASE;
sum.digits.add(new Integer(partialSum % BASE));

} // for

if (carry == 1)
sum.digits.add(new Integer(carry));
Collections.reverse(sum.digits);
digits = sum.digits;
} // method add

// Postcondition: A copy of the calling object has been returned.
public Object clone() {
VeryLongInt temp = new VeryLongInt();
temp.digits = (ArrayList) digits.clone();
return temp;
} // method clone

// Postcondition: true has been returned if the
// value of the VeryLongInt is less than the value
// of otherVeryLong. Otherwise, false
// has been returned.
public boolean less(VeryLongInt otherVeryLong) {

if (digits.size() < otherVeryLong.digits.size())
return true;
if (digits.size() > otherVeryLong.digits.size())
return false;
for (int i = 0; i < digits.size(); i++) {
if (((Integer) (digits.get(i))).intValue() < ((Integer) (otherVeryLong.digits
.get(i))).intValue())
return true;
if (((Integer) (digits.get(i))).intValue() > ((Integer) (otherVeryLong.digits
.get(i))).intValue())
return false;
} // for
return false; // the two objects have the same value
} // method less

// Postcondition: true has been returned if the value of the VeryLongInt
// is greater than the value of otherVeryLong. Otherwise,
// false has been returned.
public boolean greater(VeryLongInt otherVeryLong) {
return otherVeryLong.less(this);
} // method greater

// Postcondition: true has been returned if the value of the VeryLongInt
// is equal to the value of otherVeryLong. Otherwise,
// false has been returned.
public boolean equals(VeryLongInt otherVeryLong) {
return !less(otherVeryLong) && !otherVeryLong.less(this);
} // method equals

// Precondition: n > 0.
// Postcondition: The calling object contains the nth Fibonacci
// number.
public void fibonacci(int n) {
VeryLongInt previous = new VeryLongInt(1), current = new VeryLongInt(1), temp = new VeryLongInt();
digits.clear();
if (n <= 2)
digits.add(new Integer(1));
else {
for (int i = 3; i <= n; i++) {
temp = (VeryLongInt) current.clone();
current.add(previous);
previous = temp;
} // for
digits = current.digits;
} // else

} // method fibonacci

} // class VeryLongInt

CATIA_DELMIA_V5R2019安装包下载及安装教程破解 CATIA_V5R2019/DELMIA_V5R2019安装包下载及安装教程破解 阅读详情

相关推荐

Vienna整流器双PI闭环仿真:从SVPWM调制到中点电位平衡的实践解析

本文深入解析Vienna整流器双PI闭环仿真技术,涵盖SVPWM调制和中点电位平衡的实践细节。通过详细的MATLAB/Simulink仿真搭建流程和常见问题排查方法,帮助工程师掌握高效整流器控制策略,提升系统稳定性和动态响应性能。

weixin_29168153的博客 327

java大数运算详解【其八】大数除法

四、大数除法 /** * 返回值为{@code (this / val)}的大型整数。 * * @param 除数 * @return {@code this / val} * @throws ArithmeticException 如果{@code val}值零。 */ public BigInteger divide(BigInteger val) { if (val.mag.length < BURNIKEL...

qq_25675517的博客 2742

解决com.kingbase8.util.KSQLException: This _connection has been closed.

一个消息管理系统,系统采用kingbase8数据库,数据库采用单体模式,后台应用也采用springboot单体模式。系统正式上线后,出现几个JDBC响应的异常信息: com.kingbase8.util.KSQLException: An I/O error occurred while sending to the backend. java.net.SocketTimeoutException: Read timed out.

qq_38127559的博客 2757

BigInteger类的使用方法

先看一下JAVA API中对BigInteger的解释: public class BigInteger extends Number implements Comparable<BigInteger> Immutable arbitrary-precision integers. All operations behave as if BigIntegers were repr...

oaimgo的博客 1975

KEIL MDK 生成bin文件实战:C51与ARM双平台配置指南

本文详细介绍了在KEIL MDK开发环境中,为C51和ARM双平台自动生成BIN文件的实战方法。针对C51平台,通过srec_cat.exe工具编写批处理脚本并集成到KEIL;针对ARM平台,则利用fromelf.exe工具直接配置。文章还提供了通用脚本方案和路径、变量、版本兼容性等常见问题的避坑指南,帮助开发者高效完成嵌入式程序部署。

weixin_29188997的博客 346

Python爬虫实战:利用Playwright和反反爬技术高效抓取Bloomberg金融数据

用户行为分析(鼠标移动、点击模式)请求头检测IP频率限制WebSocket通信验证Canvas指纹识别我们的爬虫需要模拟人类行为,使用代理IP池,并合理控制请求频率。

2201_76125261的博客 1020

【笔记】Java BigInteger - Division

BigInteger to/from (uint[], bool) 用(uint[], bool)来表示有符号大数,其中uint[]是大数的绝对值,bool为false时是负数。 /// &lt;summary&gt; /// (&lt;see cref="uint"/&gt;[], &lt;see cref="bool"/&gt;) to &lt;see cref="BigInteger&quo

我是个SHA手灬莫得感情的博客 1063

CARLA仿真:自定义地图与AI车辆行为编程

CARLA仿真:自定义地图与AI车辆行为编程 ,人工智能,计算机视觉,大模型,AI,本文围绕CARLA仿真平台,介绍了其基础功能与安装方法,详解地图系统,包括预设地图的加载切换及自定义地图的创建、导入与优化。还阐述了AI车辆的创建、属性设置、销毁,以及行为控制,如交通规则遵守、路径规划、复杂行为编程和行为树应用。同时涉及传感器与车辆感知、交通场景构建、自定义地图与AI行为结合应用、高级应用,以及常见问题解决方案和学习资源,为CARLA仿真应用提供全面指导。

不踩坑,不知道坑有多深;不总结,踩过的坑白踩。 11万+

java.lang.ArithmeticException: / by zero

ArithmeticException对我来说,是一个很重要的异常。因为之前学Java异常的时候,第一个demo就是讲这个。   不对异常进行处理:   对异常进行处理:   很明显:如果一个程序从开始到结束的流程中,在中间有一个未经处理的异常,则这个异常之后的代码不会执行,程序也不会正常执行到最后并结束。   而当对这个异常进行处理之后,分成三块:try块内,异常之后的代码会跳过...

Jinxiutf666的博客 2万+

AUTOSAR从入门到精通-汽车电子电气架构(EEA)

EEA(Electrical/Electronic Architecture),电子电气架构,是首先由德尔福公司提出的,集合汽车的电子电气系统原理设计、中央电器盒的设计、连接器的设计、电子电气分配系统等设计为一体的整车电子电气解决方案的概念。通过EEA的设计,可将动力总成、驱动信息、娱乐信息等车身信息转化为实际的电源分配的物理布局、信号网络、数据网络、诊断、容错、能量管理等的电子电气解决方案。

getusushu的博客 859

[Python人工智能] 三十六.基于Transformer的商品评论情感分析 (2)keras构建多头自注意力(Transformer)模型

本专栏开始,作者正式研究Python深度学习、神经网络及人工智能相关知识。前一篇文章利用Keras构建深度学习模型并实现了情感分析。这篇文章将介绍Transformer基础知识,并通过Keras构建多头自注意力(Transformer)模型,实现IMDB电影影评数据情感分析。基础性文章,希望对您有所帮助!...

杨秀璋的专栏 4909

【java基础】大数处理 BigInteger、BigDecimal的使用

我们都知道,在java中整数最大的也就是long型,浮点数最大的也就是double。它们的精度都是有限的,如果遇到更大或者要求小数点后精确到1000位该怎么做呢?在java中有无限精度的数据类型吗?当然是有的,java提供了BigInteger和BigDecimal。这两个类可以处理包含任意长度数字序列的数值。BigInteger类实现任意精度的整数运算BigDecimal实现任意精度的浮点数运算。

秃头披风侠的博客 1234

Autosar代码包初识 2 - 如何编译Vector包内Demo工程

Vetcor autosar代码包Demo工程编译,GreenHills,RH850,Autosar,Davinci COnfigurator

weixin_42412049的博客 5185

JAVA - JAVA大数处理BigInteger与BigDecimal

https://blog.youkuaiyun.com/hqd_acm/article/details/5751686

bupa900318的博客 1914

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

处理大数的Java API之BigInteger和BigDecimal

当我们遇到很大的一串数字的时候用long就放不开了,于是Java有一个API叫BigInteger和BigDecimal可以很方便的用来处理很长的数字。 可以使用BigInteger操作大整数 整数 可以使用BigDecimal指定小数的保留位数 小数 BigInteger 首先我们来看一下BigInteger的一些常用方法,如下面代码所示,代码中的注释详尽的介绍了它的用法 package cn.shi; import java.math.BigInteger; public class Test

Go Tum's Bolg 248

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

java大数bigdecimal,JAVA大数处理(BigInteger,BigDecimal)

Java中有两个类BigInteger和BigDecimal分别表示大整数类和大浮点数类。这两个类都在java.math.*包中,因此每次必须在开头处引用该包。Ⅰ基本函数:1.valueOf(parament);//将参数转换为制定的类型2.add(); //大整数相加3.subtract(); //相减4.multiply(); //相乘5.divi...

weixin_42352453的博客 290

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

java中的大数处理-BigInteger和BigDecimal

【转】JAVA大数处理(BigInteger,BigDecimal) 转自:http://hi.baidu.com/shouzhewei/item/ad630c7261c44418d0dcb312 在用C或者C++处理大数时感觉非常麻烦,但是[color=red]在JAVA中有两个类BigInteger和BigDecimal分别表示大整数类和大浮点数类,至于两个类的对象能表示最大...

yimenghust的博客 187

Java中大数处理方案(BigInteger和BigDecimal)的理解学习

Java提供了两个用于高精度计算BigInteger和BigDecimal。这两个类包含的方法、提供的操作与对基本类型所能执行的操作相似,只不过是以方法调用方式取代运算符方式来实现。等于是用速度换取了精度。BigInteger支持任意精度的整数,在运算中可以准确地表示任何大小的整数值,而不会丢失任何信息。BigDecimal支持任何精度的定点数,可以用它进行精确的货币计算。它们都扩展Number类且实现Comparable接口,可以使用或。...

爱学习的大雄的博客 764
上一篇: Map集合中value()方法与keySet()、entrySet()区别
下一篇: java中的Iterator和Iterable 区别 博客分类: java基础 iteratoriterable java.lang.Iterable java.util.Iterator 来
Jimmy-尹
博客等级 码龄9年 26粉丝 15原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值