大数问题 Java

c++和c对大数的处理很麻烦,但Java中有两个类:BigInteger和BigDecimal分别用于处理大整数和大浮点数,具体表示范围……emmm不懂,总之就是很大,这两个类都可以通过调用java.math.*来使用

(不会Java就很尴尬,来学学简单的Java的计算处理)

Java与c/c++一些语法上的不同和基本用法:

1.头文件:

1 import java.math.*;
2 import java.util.*;

2.程序主体  //基本的读入输出操作

public class Main
{  
         public static void main(String args[])
       {  
              Scanner cin = newScanner(System.in);
while(cin.hasNext)
{
int n;
BigInteger m;
n=cin.nextInt();
m=cin.nextBigInteger();
Systerm.out.print(m);
}
    }  
}

3.与c/c++

while()语句: while(n-->0)   // while(n--)

EOF: 普通的数:while(cin.hasNextInt())   //相当于!=EOF,第一个为整数

            大数:while(cin.hasNextBigInteger())  //第一个为大数

System.out.print(m.toString());    //转化为string

System.out.print(n);  //输出n;

System.out.println(n); //输出n并换行

System.out.println(“Case#”+(t++)+":"+" "+c.toString(2));  //t为int,c为大数,输出数据之间用+连接

System.out.print(" ");或 System.out.println();   //换行

System.out.print(" ");  //输出空格

4.基本常量

A=BigInteger.ONE 1

B=BigInteger.TEN 10

C=BigInteger.ZERO 0

5.大数相关计算:

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.public int compareTo();

14.boolean equals(); 是否相等

15.BigInteger构造函数:
一般用到以下两种:
BigInteger(String val);
将指定字符串转换为十进制表示形式;
BigInteger(String val,int radix);
将指定基数的 BigInteger 的字符串表示形式转换为 BigInteger

 相关题目:hdu 1002 hdu 1042 hdu1047 hdu 1063 hdu 1316 hdu 1715 hdu 1753

原文地址:https://www.cnblogs.com/Egoist-/p/7653035.html