Daily practice of C language - Day 82: King Shehan's miscalculation

C language daily practiceFebruary
22, 2022

Topic description

According to legend, chess was invented by Dayil, the prime minister of the ancient Indian king of Shehan. King Shehan was very fond of chess, and decided to let the prime minister choose what kind of reward. The wise prime minister pointed at the 8×8 chess board with a total of 64 squares and said: Your Majesty, please give me some wheat. Just put 1 grain in the first square of the chessboard, 2 grains in the second square, and 4 grains in the third square. After that, each square is doubled from the previous square. After placing 64 squares on the chessboard, I will Thank you so much. King Shekhan asked for a sack of wheat, and he wanted to fulfill his promise. Please program to find out how much wheat the king needs to give to his prime minister in total.

problem analysis

Put 1 grain in the first square and 2 grains in the second square, each time it is twice as large as the previous square. There are 64 squares in a chessboard, so we can get the following formula:
insert image description here
It can be seen that this should be a very large The number of , if you are very proficient in binary operations, you can even see the result of this formula, yes, it is 2 64 -1 . (To give a simple example: the binary number 1111 is equivalent to decimal 2 0 +2 1 +2 2 +2 3 =2 4 -1=15)

To represent 2 64 -1 in C language , you can use the unsigned long long type.

The following lists the number of bytes occupied by variables of various types on 32-bit machines and 64-bit machines under the GCC compiler:

type of data 32bit 64bit
char 1 1
short 2 2
int 4 4
unsigned int 4 4
long 4 8
unsigned long 4 8
long long 8 8
char* 4 8
float 4 4
double 8 8

My compiler is 32-bit, so I have to use unsigned long long (the range of long long is -2 63 ~2 63 -1, which cannot represent 2 64 -1.
There are double types on the Internet, but I am in my compilation The correct result cannot be obtained on the device.

Code

#include <stdio.h>

int main()
{
    
    
    unsigned long long sum = 1, tmp = 1;
    int i = 0;
    //从第二个格子开始算,总共63个格子
    for(i = 1; i < 64; i++)
    {
    
    
        tmp *= 2;
        sum += tmp;
    }
    printf("国王总共需要将%llu粒麦子赏赐给他的宰相\n", sum);
    return 0;
}

operation result

insert image description here

online reference

For reference only (the original answer is wrong, the code may be ok)
Original link: http://c.biancheng.net/cpp/html/3321.html

#include <stdio.h>
#include <math.h>
int main()
{
    
    
    double sum = 0;  /*定义double型变量sum存放累加和*/
    int i;
    /*使用循环求累加和*/
    for( i=1; i<=64; i++ )
        sum = sum + pow(2.0, (i-1));  /*注意变量为double型*/
    printf("国王总共需要赏赐给宰相的麦子数为:\n%f\n", sum);  /*打印结果*/
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43772810/article/details/123071130