JAVA入门之大数实现模板(全)

欢迎访问https://blog.csdn.net/lxt_Lucia~~

宇宙第一小仙女\(^o^)/~~萌量爆表求带飞=≡Σ((( つ^o^)つ~ dalao们点个关注呗~~

 

恭喜本人申请使用权成功哇哈哈哈 ~~     本篇前半部分知识点转载至 “星博” :

https://blog.csdn.net/Akatsuki__Itachi/article/details/81152232

(转+原)

 


转:

在ACM竞赛里难免会遇到一些大数(即超大数字!)的问题,但是对于ACMers来说,彼时还没有学过java,只会敲一手C/C++(比如我的大一),这篇博客就简单讲一下用java来实现大数的相关操作

关于eclipse的使用,这里也捎带一提。

配置了jdk并安装好eclipse之后(什么?怎么配置jdk?当然要点这里了!(ubuntu系统))

进入到eclipse界面

第一步:file->new->java project->起名->finish

第二步:进入到刚才建的工程里,右键src->new->package->起名->finish

第三步:进入到刚才建的package里,右键name->new->class->起名(这里起名要注意,因为比赛时如果交java代码,这里的类名就要命名为Main,区分大小写
 

下面就开始写我们的代码了

先从最简单的来说:

 

1.输出hello world

package BigInteger;
public class Main {
	public static void main(String args[]) {
		System.out.println("Hello world");
	}
}

关于上面的package BigInteger,是打包发送的意思,编译运行需要这一行,但提交代码时不需要粘贴。

 

2.计算a+b

package BigInteger;
import java.util.*;//导包,相当于c/c++里的头文件
public class Main {
	public static void main(String args[]) {
		
		Scanner cin = new Scanner(System.in);
		
		int a,b;
		a = cin.nextInt();
		b=cin.nextInt();
		int ans = a + b;
		System.out.println(ans);
	}
}

 

3.多组输入 a b

package BigInteger;
import java.util.*;
public class Main {
	public static void main(String args[]) {
		
		Scanner cin = new Scanner(System.in);
		
		int a,b;
		while(cin.hasNext()) {
			a=cin.nextInt();
			b=cin.nextInt();
			int ans=a+b;
			System.out.println(ans);
		}
	}
}

 

下面就开始说大数的相关操作

首先我们需要导包,即BigIntegr类 BigDecimal类 所在的包

import java,math.*;

*就代表导入包math里面所有的类,如果你不喜欢看到 *

那么你也可以写 import java,math.BigInteger; import java,math.BigDecimal;

 

1.大整数的加减乘除求余计算

package BigInteger;
import java.util.*;
import java.math.*;
public class Main {
	public static void main(String args[]) {
		
		Scanner cin = new Scanner(System.in);
		
		BigInteger a , b;
		a=cin.nextBigInteger();
		b=cin.nextBigInteger();
		
		BigInteger ans_add,ans_sub,ans_mul,ans_div,ans_mod;
		
		ans_add = a.add(b); //a+b
		ans_sub = a.subtract(b); //a-b
		ans_mul = a.multiply(b); //a*b
		ans_div = a.divide(b); //a/b
		ans_mod = a.mod(b); //a%b
		System.out.println("a + b = "+ans_add);
		System.out.println("a - b = "+ans_sub);
		System.out.println("a * b = "+ans_mul);
		System.out.println("a / b = "+ans_div);
		System.out.println("a % b = "+ans_mod);
		
	}
}

运行结果如下:

 

下面举个求阶乘的例子:

package BigInteger;
import java.util.*;
import java.math.*;
public class Main {
	
	public static BigInteger factorial(BigInteger n){  
      	  	BigInteger bd1 = new BigInteger("1");
      		BigInteger bd2 = new BigInteger("2");
        	BigInteger result = bd1;
        	while(n.compareTo(bd1) > 0){
            		result = result.multiply(n);  
            		n = n.subtract(bd1); 
        	}   
        	return result;   
        }  
	
	public static void main(String args[]) {
		
		Scanner cin = new Scanner(System.in);
		
		BigInteger n;
		n=cin.nextBigInteger();
		
		BigInteger ans;
		ans = factorial(n);
		System.out.println("n的阶乘为: "+ans);
		
	}
}

 

关于BigDecimal的用法大致上和BigInteger一样。

不过这里需要提一下,在进行大浮点数运算的时候,小数点后面可能会含有多余的后导0

比如0.5000,在题目要求中可能只需要输出0.5

当然,有的题目可能还会要求小数点前面的0也要去掉,输入.5

这时候我们就需要去除掉后导0

方法如下:

String str;
str=ans.stripTrailingZeros().toPlainString();//去除后导0
//ans为大浮点数运算后得到的答案
//如果小数点前面的0也需要去掉,那么输出的时候处理一下即可:
if(str.charAt(0)=='0')
        System.out.println(str.substring(1));
else
        System.out.println(str);

 


原:

具体模板上述已经说的很详细了,通过做题这里再补充两点:

 

1.开数组

假设定义一个数组a[100],应该采用如下定义方式。

代码:

BigInteger [ ]a = new BigInteger[100];

 

2.substring, valueOf, intValue 三个的作用解释及区分

咱们举个栗子来解释这个知识点:

int len = 50;
len = Integer.valueOf ( str.substring(j+1) ).intValue( )

比如说有个String str = "12345" ;

(1)substring函数是取一个string子串,如果j=1,那么str.substring ( j+1 ) 就是取从第2位开始的子串,所以str.substring ( j+1 ) 等于“345”。

(2)valueOf是Integer类的一个静态方法,它是把一个string参数转换为Integer类型,那么经过Integer.valueOf ( "345" ) 转换,345就是一个Integer类型了。

(3)intValue函数是将一个integer类型转换成原始类型int,所以最后len就等于345了。

 

 

那么下面咱们举几个栗子来实践一下叭~~


例1:Integer Inquiry

Decription

One of the first users of BIT’s new supercomputer was Chip Diller. He extended his exploration of powers of 3 to go from 0 to 333 and he explored taking various sums of those numbers. “This supercomputer is great,” remarked Chip. “I only wish Timothy were here to see these results.” (Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky apartments on Third Street.) Input The input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger. Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no VeryLongInteger will be negative). The final input line will contain a single zero on a line by itself. Output Your program should output the sum of the VeryLongIntegers given in the input.

Sample Input

123456789012345678901234567890

123456789012345678901234567890

123456789012345678901234567890

0

Sample Output

370370367037037036703703703670

 

解析:

       就是简单的a+b类型,套用a+b模板和多组输入模板即可,但需注意给ans赋0不得采用ans=0的方式,而应该采用BigInteger ans = new BigInteger("0"),判断是否等于0的时候也不能直接和比较,而应该先将0赋给另一个变量,然后将两个变量做比较。

 

代码:

package BigInteger;
import java.util.*;
import java.math.*;

public class Main {
	public static void main(String args[]) {
		Scanner cin = new Scanner(System.in);
		BigInteger a , b;
		BigInteger ans = new BigInteger("0");
		b = new BigInteger("0");
		while ( cin.hasNext() ) {
		     a = cin.nextBigInteger();
		     if ( a.compareTo(b) != 0 )
		         ans = ans.add(a);
		     else break;
		}
		System.out.println(ans);
	}
}

 

什么?太简单了?不急,咱们循序渐进。

 

例2:Product

Decription

The problem is to multiply two integers X, Y . (0 ≤ X, Y < 10250)

Input

The input will consist of a set of pairs of lines. Each line in pair contains one multiplyer.

Output

For each input pair of lines the output line should consist one integer the product.

Sample Input

12

12

2

222222222222222222222222

Sample Output

144 444444444444444444444444

 

解析:

       套用多组输入模板和计算加减乘除求余模板即可~

 

代码:

package BigInteger;
import java.util.*;
import java.math.*;

public class Main {
	public static void main(String args[]) {
		Scanner cin = new Scanner(System.in);
		BigInteger a , b;
		while(cin.hasNext()) {
		a=cin.nextBigInteger();
		b=cin.nextBigInteger();
		BigInteger ans_mul;
		ans_mul = a.multiply(b);
		System.out.println(ans_mul);
		}
	}
}

 

什么?比上一道题还简单?哼!你完了!我要给你设坑!哼!!!

 

例3:Overflow

Decription

Write a program that reads an expression consisting of two non-negative integer and an operator. Determine if either integer or the result of the expression is too large to be represented as a “normal” signed integer (type integer if you are working Pascal, type int if you are working in C).

Input

An unspecified number of lines. Each line will contain an integer, one of the two operators ‘+’ or ‘*’, and another integer.

Output

For each line of input, print the input followed by 0-3 lines containing as many of these three messages as are appropriate: ‘first number too big’, ‘second number too big’, ‘result too big’.

Sample Input

300 + 3

9999999999999999999999 + 11

Sample Output

300 + 3

9999999999999999999999 + 11

first number too big

result too big

 

解析:

首先对于输出,一定注意:

1. 要先把输入的内容输出,然后再following跟上0~3行结果。

2. 0~3行的意思是:如果第一个数太大,就输出first number too big,然后如果第二个数太大,再输出second number too big,如果 ’+‘ 或者 ' * ' 的结果太大,就再输出result too big,所以输出的结果最少有0个,即三个数都不够大,最多有3个,即3个数都太大,所以样例中的first number too big 和 result too big 都是第二组样例输出的,第一组样例输出了0行。

3. 看清题目要求,计算的结果要按照输入的 + 或者 * 来计算,并非每组都要计算 + 和 * ,除非后台水,有的样例计算 + 可能不超,计算 * 可能就超了。

4. 这里的最大指的是INF=2e31-1,也就是INT_MAX,存在于<limits>中,而非0x3f3f3f3f ( 我WA了好几次都是这个原因...)。

5. 学JAVA就忘了C嘛!!!大数当然也可以做,不过这题用double就可以解决了,double可开比long long int 还大,可以先用字符串直接存进3个数组,然后用atof()函数直接将字符串转化成值,比如串123456就可直接转化为值123456,很方便~

 

代码:

#include<math.h>
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
#include<queue>
const int INF=2e31-1;

using namespace std;

int main()
{
    double a,b;
    char c[10000],d[10000],s[5];
    while(~scanf("%s %s %s",c,s,d))
    {
        a=atof(c);
        b=atof(d);
        printf("%s %s %s\n",c,s,d);
        if(a>INF)
            printf("first number too big\n");
        if(b>INF)
            printf("second number too big\n");
        if((s[0]=='+'&&a+b>INF)||(s[0]=='*'&&a*b>INF))
            printf("result too big\n");
    }
    return 0;
}

 

肿么样~

下面这题有点点小小麻烦,除0问题~

 

例4:Exponentiation

Decription

Problems involving the computation of exact values of very large magnitude and precision are common. For example, the computation of the national debt is a taxing experience for many computer systems. This problem requires that you write a program to compute the exact value of Rn where R is a real number (0.0 < R < 99.999) and n is an integer such that 0 < n ≤ 25.

Input

The input will consist of a set of pairs of values for R and n. The R value will occupy columns 1 through 6, and the n value will be in columns 8 and 9.

Output

The output will consist of one line for each line of input giving the exact value of Rn. Leading zeros and insignificant trailing zeros should be suppressed in the output.

Sample Input

95.123 12

0.4321 20

5.1234 15

6.7592 9

98.999 10

1.0100 12

Sample Output

548815620517731830194541.899025343415715973535967221869852721

.00000005148554641076956121994511276767154838481760200726351203835429763013462401

43992025569.928573701266488041146654993318703707511666295476720493953024

29448126.764121021618164430206909037173276672

90429072743629540498.107596019456651774561044010001 1.126825030131969720661201

 

解析:

套用多组输入模板和除0模板即可~ 但仍易犯直接赋值的小错误。除0要注意BigDecimal而非BigInteger,且要用串。

 

代码:

package BigInteger;
import java.util.*;
import java.math.*;

public class Main {
	public static void main(String args[]) {
		Scanner cin = new Scanner(System.in);
		BigDecimal a , ans = new BigDecimal("1");
		int b;
		String s,str;
		while ( cin.hasNext() ) {
			ans = new BigDecimal("1");
		    a = cin.nextBigDecimal();
		    b = cin.nextInt();
		  while(b>0) {
			b = b-1;
	    	ans = ans.multiply(a);
		  }
		  str=ans.stripTrailingZeros().toPlainString();
		  if(str.charAt(0)=='0')
		    System.out.println(str.substring(1));
		  else
		    System.out.println(str);
		}
	}
}

 

下面是最后一题咯~ 简单一点放松一下好了~ 护发从现在做起~

 

例5:If We Were a Child Again

Decription

“Oooooooooooooooh! If I could do the easy mathematics like my school days!! I can guarantee, that I’d not make any mistake this time!!” Says a smart university student!! But his teacher even smarter – “Ok! I’d assign you such projects in your software lab. Don’t be so sad.” “Really!!” – the students feels happy. And he feels so happy that he cannot see the smile in his teacher’s face. The first project for the poor student was to make a calculator that can just perform the basic arithmetic operations. But like many other university students he doesn’t like to do any project by himself. He just wants to collect programs from here and there. As you are a friend of him, he asks you to write the program. But, you are also intelligent enough to tackle this kind of people. You agreed to write only the (integer) division and mod (% in C/C++) operations for him.

Input

Input is a sequence of lines. Each line will contain an input number. One or more spaces. A sign (division or mod). Again spaces. And another input number. Both the input numbers are nonnegative integer. The first one may be arbitrarily long. The second number n will be in the range (0 < n < 2 31).

Output

A line for each input, each containing an integer. See the sample input and output. Output should not contain any extra space.

Sample Input

110 / 100

99 % 10

2147483647 / 2147483647

2147483646 % 2147483647

Sample Output

1

9

1

2147483646

 

解析:

水题,套用加减乘除求余模板即可~ 注意比较要用compareTo,并且严格区分大小写。

 

代码:

package BigInteger;
import java.util.*;
import java.math.*;

public class Main {
	public static void main(String args[]) {
		Scanner cin = new Scanner(System.in);
		BigInteger a , b, ans = new BigInteger("0");
		String s;
		while ( cin.hasNext() ) {
		a = cin.nextBigInteger();
		s = cin.next();
		b = cin.nextBigInteger();
		if( s.compareTo("+") == 0)
	    	ans = a.add(b);
		if( s.compareTo("-") == 0)
	    	ans = a.subtract(b);
		if( s.compareTo("*") == 0)
	    	ans = a.multiply(b);
		if( s.compareTo("/") == 0)
		    ans = a.divide(b); 
		if( s.compareTo("%") == 0)
	     	ans = a.mod(b); 
		System.out.println(ans);
		}
	}
}

 

例6:Train Problem II 

Description

As we all know the Train Problem I, the boss of the Ignatius Train Station want to know if all the trains come in strict-increasing order, how many orders that all the trains can get out of the railway. 

Input

The input contains several test cases. Each test cases consists of a number N(1<=N<=100). The input is terminated by the end of file. 

Output

For each test case, you should output how many ways that all the trains can get out of the railway. 

Sample Input

1
2
3
10

Sample Output

1
2
5
16796

Hint

The result will be very large, so you may not process it by 32-bit integers.

 

解析:

本题为卡特蓝数模板题,这里顺便提示一下卡特蓝数绝大多数都用大数来做,用普通做法需要许多重优化更为麻烦,本篇主讲JAVA大数,重心暂且不放在卡特蓝数等,相关内容敬请期待,近期会持续更新ing......本题主要学一下开数组的方法,BigInteger [ ]a = new BigInteger[105];  .valueOf的用法可参考本篇“原创”部分最开始关于.valueOf,substring,intValue三个的作用区分~

代码:

package yuzhoudiyiwudixiaoxiannv;

import java.util.*;
import java.math.*;

public class Main {
	public static void main(String args[]) {
		Scanner cin = new Scanner(System.in);
		BigInteger []a = new BigInteger[105];
		a[0] = new BigInteger("1");
		a[1] = new BigInteger("1");
		for(int i = 2;i <= 100;i++)
			a[i] = a[i-1].multiply(BigInteger.valueOf(4 * i - 2)).divide(BigInteger.valueOf( i + 1 ));
		while ( cin.hasNext() ) {
			int n=cin.nextInt();
		    System.out.println(a[n]);
		}
	}
}

 

还是觉得很Magic的~ 毕竟刚刚接触JAVA嘛.....

 

感谢dalao访问https://blog.csdn.net/lxt_Lucia~~

持续更博ing ~ ~ ~ 

宇宙第一小仙女\(^o^)/~~萌量爆表求带飞=≡Σ((( つ^o^)つ~dalao们点个关注呗~~

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值