【转】Java BigInteger(大数,ACM比赛专用)

本文详细介绍了Java中处理大数的技巧,通过BigInteger和BigDecimal类实现大整数和大浮点数的运算,包括加、减、乘、除、取余、求幂等操作,并提供了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用c或者C++处理大数比较麻烦,于是决心学习一下JAVA中大数运算。

先下载一个eclipse,具体的用法去问度娘吧

JAVA中有两个类BigIntegerBigDecimal分别表示大整数类和大浮点数类

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

下面说说几个常用的用法

1. 

   int a=3;

  BigInteger b=BigInteger.valueOf(a);

  则b=3;

2.

String s="-123459999999999999999999";
BigInteger c=new BigInteger(s,10);

把字符串转换成10进制的大数;

3.

BigInteger a=new BigInteger("234");
BigInteger b=new BigInteger("567");

System.out.println(a.add(b));

2个大数相加,a没变。

subtract(); 相减   multiply(); 相乘   divide();    相除取整   remainder(); 取余  pow();   a.pow(b)=a^b  gcd();   最大公约数

abs(); 绝对值  negate(); 取反数  mod(); a.mod(b)=a%b=a.remainder(b);   max(); min();  boolean equals(); 是否相等

3.

读入:

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

Scanner cin=new Scanner(System.in);
while(cin.hasNext())//相当于EOF
{
int n;
BigInteger m;
n=cin.nextInt();
m=cin.nextBigInteger();
System.out.println(n);
System.out.println(m);
}

插入写的代码

复制代码

 1 import java.math.BigInteger;
 2 import java.util.Scanner;
 3 public class hello {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7          //System.out.println("hello");
 8         //int num=3;
 9         //System.out.println("hell0"+num);
10        //int a=3;
11        //BigInteger b=BigInteger.valueOf(a);
12        //System.out.println(b);
13        //String s="-123459999999999999999999";
14        //BigInteger c=new BigInteger(s,10);
15        //BigInteger c=new BigInteger("12345"); 
16         //BigInteger a=new BigInteger("234");
17         //BigInteger b=new BigInteger("567");
18         //BigInteger c=a+b;
19         //subtract();
20         //multiply();
21         //divide();
22         //remainder();
23         //pow();
24         //gcd();
25         //System.out.println(a.add(b));
26         Scanner cin=new Scanner(System.in);
27         while(cin.hasNext())
28         {
29             //int n;
30             BigInteger m,n;
31             n=cin.nextBigInteger();
32             m=cin.nextBigInteger();
33             boolean coper=n.equals(m);
34             System.out.println(n);
35             System.out.println(m);
36             System.out.println(coper);
37         }
38        
39     }
40 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值