Задачи по программированию на шахматной доске. Chessboard programming problems. And other problems.
Arranged probability
If a box contains twenty-one coloured discs, composed of fifteen blue discs and six red discs, and two discs were taken at random,
it can be seen that the probability of taking two blue discs, P(BB) = (15/21)×(14/20) = 1/2.
The next such arrangement, for which there is exactly 50% chance of taking two blue discs at random, is a box containing
eighty-five blue discs and thirty-five red discs.
By finding the first arrangement to contain over 1012 = 1,000,000,000,000 discs in total, determine
the number of blue discs that the box would contain.
The simple solution in C++.
Let $x$ be blue disks and $y$ be total number of disks.
$P(BB) = \dfrac{x(x-1)}{y(y-1)} = \dfrac{1}{2} (1)$
$y > 10^{12} (2)$
$x$ and $y$ are too large to compare with 1. Therefore, equation (1) can be
rewritten
$P(BB) = \dfrac{x^2}{y^2} = \dfrac{1}{2} (3)$
The program will iterate in this range: $ 10^{13} > y > 10^{12} (4)$
and x iteration range can be seen as $ \dfrac{y}{\sqrt{2}} < x < 10 \dfrac{y}{\sqrt{2}} (5)$
based on equeation (3).
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <math.h>
#include <ctime>
#include <string>
int main(int argc, char* argv[])
{
const clock_t begin_time = clock();
long long y = (long long) pow(10, std::stoi(argv[1]));
std::cout << "Calculation for " << y << std::endl;
long long nCounter = 0;
bool bSolution = false;
long double sqrt2 = sqrt(2);
for (long long j = y; j < y * 10; j++)
{
long long nTemp = j * (j - 1);
long long nTemp1 = (long long) floor(j / sqrt2);
for (long long i = nTemp1; i < nTemp1 * 10; i++)
{
long long nTemp2 = 2 * i * (i - 1);
nCounter++;
if (nTemp == nTemp2)
{
std::cout << "Solution is found for x=" << i << " and y=" << j << std::endl;
bSolution = true;
break;
}
else if (nTemp < nTemp2)
{
break;
}
}
if (bSolution) break;
}
if (!bSolution) std::cout << "No solution was found." << std::endl;
float dtDifference = float(clock() - begin_time) / CLOCKS_PER_SEC;
std::cout << "The number of iterations is " << nCounter << std::endl;
std::cout << "Execution time is " << dtDifference << " seconds." << std::endl;
return 0;
}
This C++ program runs with the results:
Calculation for 1000000000000
Solution is found for x=756872327473 and y=1070379110497
The number of iterations is 1265225536232
Execution time is 879.357 seconds.
$x=756872327473 \approx 10^{11.879}$
$y=1070379110497 \approx 10^{12.029}$