Algorithm exercise: put wheat on the chessboard

Problem Description

There are 64 squares in chess, please put 1 grain of wheat on the first square, 2 grains on the second square, 4 grains on the third square, and 8 grains on the fourth square , ... the number of the next grid is twice that of the previous grid, until all the checkerboard grids are placed.
Please use a computer to accurately calculate how many grains of wheat are needed?

Code

fun main(){
    
    
    // 公式求 
    var sum:BigInteger = BigInteger.valueOf(0)
    var m: BigInteger
    sum = BigInteger.valueOf(2).pow(64) - BigInteger.valueOf(1)
    println("总数== $sum")
    //循环求
    sum  = BigInteger.valueOf(0)
    for (index in 1..64) {
    
    
             m = BigInteger.valueOf(1)
        for (index1 in 1 until index){
    
    
            m.multiply(BigInteger.valueOf(2)).also {
    
     m = it }
        }
        sum+=m
    }
    print("总数== $sum")
}
The result is relatively large, so you need to useBigInteger

Guess you like

Origin blog.csdn.net/TLuffy/article/details/124471880