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

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);
    }
}
复制代码

 

posted @   抹茶泡芙  阅读(54)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示