According to an ancient legend, the sage who invented chess demanded such a quantity of wheat from the Persian Shah that they could cover the chessboard, putting 1 grain on the first cell, 2 on the second cell, 4 on the third, etc. . for every next two more than the previous one. How much grain can a chessboard cover?
Here is the code:
#include <stdio.h> #include <math.h> #include <conio.h> void main() {long int s, k, i; clrscr; s=1; for(i=1;i<=64;i++) {k=exp(i*log(2)); s+=k } printf("Kol-vo zeren=%50d\n",s); getch(); }
The problem is that the code gives the wrong answer, and yes even with a minus. I do not understand why, and judging by the benefits - the cycle is set correctly
k
overflow. When reaching too large values of integer variables go into the negative. Read, for example, this discussion . (There's about Java, but with C ++ the same story.) - VladDlong
takelong long
. This will help for a while. 2. Use the floating point type instead of the integer type. There are even more limits. But all the same, sooner or later you will come to the limit. 3. Use special arithmetic types of arbitrary precision. (for example, GMP or boost :: multiprecision ). There are no such types built into the language. - VladD