首页 > 其他分享 > 棋盘放麦子 --------- 大整数(BigInteger详解)

棋盘放麦子 --------- 大整数(BigInteger详解)

时间:2023-01-11 17:46:52浏览次数:37  
标签:麦子 BigInteger val 对象 valueOf 详解 --------- public

BigInteger类

  用java.math包中的BigInteger类的对象,可以使用构造方法public BigInteger(String val)构造一个十进制的BigInteger对象。该构造方法可以发生NumberFormatException异常,也就是说,字符串参数val中如果含有非法数字字符就会发生NumberFormatException异常。以下是BigInteger类的常用方法:

  • public BigInteger add(BigInteger val): 返回当前对象与val的和.
  • public BigInteger subtract(BigInteger val):返回当前对象与val的差。
  • public BigInteger multiply(BigInteger val):返回当前对象与val的积。
  • public BigInteger divide(BigInteger val):返回当前对象与val的商。
  • public BigInteger remainder(BigInteger val):返回当前对象与val的余。
  • public int compareTo(BigInteger val): 返回当前对象与val的比较结果,返回值是1、-1或0,分别表示当前对象大于、小于或等于val。
  • public BigInteger abs():返回当前整数对象的绝对值。
  • public BigInteger pow(int a):返回当前对象的a次幂.
  • public String toString():返回当前对象十进制的字符串表示。
  • public String toString(int p):返回当前对象p进制的字符串表示。
赋值表达1:  
BigInteger sum=BigInteger.valueOf(1); BigInteger a = BigInteger.valueOf(1); BigInteger n= BigInteger.valueOf(2);

赋值表达2:
BigInteger a = new BigInteger(input1);
BigInteger b = new BigInteger(input2);

 

题目描述

你一定听说过这个故事。国王对发明国际象棋的大臣很佩服,问他要什么报酬,大臣说:请在第 1 个棋盘格放 1 粒麦子,在第 2 个棋盘格放 2 粒麦子,在第 3 个棋盘格放 4 粒麦子,在第 4 个棋盘格放 8 粒麦子,......后一格的数字是前一格的两倍,直到放完所有棋盘格(国际象棋共有 6464 格)。

国王以为他只是想要一袋麦子而已,哈哈大笑。

当时的条件下无法准确计算,但估算结果令人吃惊:即使全世界都铺满麦子也不够用!

请你借助计算机准确地计算,到底需要多少粒麦子。

import java.math.BigInteger;
import java.util.Scanner;
// 1:无需package
// 2: 类名必须Main, 不可修改
public class Main {
    public static void main(String[] args) {
        BigInteger sum=BigInteger.valueOf(1);
        BigInteger a = BigInteger.valueOf(1);
        BigInteger n= BigInteger.valueOf(2);
        for(int i=2;i<=64;i++){
            a=a.multiply(n);
            sum=sum.add(a);
        }
        System.out.println(sum);
    }
}

 

标签:麦子,BigInteger,val,对象,valueOf,详解,---------,public
From: https://www.cnblogs.com/mcpf/p/17044485.html

相关文章