Skip to content

Instantly share code, notes, and snippets.

@haruo-wakakusa
Created January 25, 2021 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haruo-wakakusa/a2fad1b46bf2f5df5545e36d79cae71e to your computer and use it in GitHub Desktop.
Save haruo-wakakusa/a2fad1b46bf2f5df5545e36d79cae71e to your computer and use it in GitHub Desktop.
円周率を正確に求めるプログラム
/*
* 円周率を正確に求めるプログラム
*
* - 半径が10^nの円の第一象限を縦横に10^n分割してその面積の下限と上限を求めます
*/
#include <cstdint>
#include <cmath>
#include <iostream>
using INT = std::int32_t;
constexpr INT N = 4;
constexpr INT M = std::pow(10, N);
constexpr INT MM = M * M;
INT calc_lower() {
// 下限を求める。各分割の左上が円に含まれるならば積分する。
INT sum = 0;
for (INT i = 1; i <= M; ++i)
for (INT j = 1; j <= M; ++j)
if (i * i + j * j <= MM)
sum += 1;
return sum * 4;
}
INT calc_upper() {
// 上限を求める。各分割の右下が円に含まれないならば積分する。
INT sum = 0;
for (INT i = 0; i < M; ++i)
for (INT j = 0; j < M; ++j)
if (i * i + j * j > MM)
sum += 1;
return (MM - sum) * 4;
}
int main() {
std::cout << "n = " << N << std::endl;
std::cout << "lower = " << calc_lower() << " / " << MM << std::endl;
std::cout << "upper = " << calc_upper() << " / " << MM << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment