Created
December 5, 2017 05:42
-
-
Save komasaru/b2bef16c69cc0ecb394ebb9521c7bc9e to your computer and use it in GitHub Desktop.
C++ source code to compute Napier's constant.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/********************************************* | |
* ネイピア数 e (自然対数の底)計算 | |
*********************************************/ | |
#include <iostream> // for cout | |
#include <stdio.h> // for printf() | |
#define L 1000 // 算出桁数 | |
#define L1 ((L / 8) + 1) // 配列サイズ | |
#define L2 (L1 + 1) // 配列サイズ + 1 | |
#define N 451 // 計算項数 | |
using namespace std; | |
/* | |
* 計算クラス | |
*/ | |
class Calc | |
{ | |
// 各種変数 | |
int k, i; // LOOP インデックス | |
int carry, borrow; // 繰り上がり、借り | |
long w; // 被乗数、被除数ワーク | |
long r; // 剰余ワーク | |
public: | |
// 計算 | |
void calc(); | |
// ロング + ロング | |
void ladd(int *, int *, int *); | |
// ロング / ショート | |
void ldiv(int *, int, int *); | |
// 結果出力 | |
void display(int *); | |
}; | |
/* | |
* 計算 | |
*/ | |
void Calc::calc() | |
{ | |
// 配列宣言 | |
int s[L2 + 2], a[L2 + 2]; | |
// 配列初期化 | |
s[0] = a[0] = 1; | |
for (k = 1; k <= L2; k++) | |
s[k] = a[k] = 0; | |
// 計算 | |
for (k = 1; k <= N; k++) { | |
ldiv(a, k, a); | |
ladd(s, a, s); | |
} | |
// 結果出力 | |
display(s); | |
} | |
/* | |
* ロング + ロング | |
*/ | |
void Calc::ladd(int a[], int b[], int c[]) | |
{ | |
carry = 0; | |
for (i = L2; i >=0; i--) { | |
c[i] = a[i] + b[i] + carry; | |
if (c[i] < 100000000) { | |
carry = 0; | |
} else { | |
c[i] -= 100000000; | |
carry = 1; | |
} | |
} | |
} | |
/* | |
* ロング / ショート | |
*/ | |
void Calc::ldiv(int d[], int e, int f[]) | |
{ | |
r = 0; | |
for (i = 0; i < L2; i++) { | |
w = d[i]; | |
f[i] = (w + r) / e; | |
r = ((w + r) % e) * 100000000; | |
} | |
} | |
/* | |
* 結果出力 | |
*/ | |
void Calc::display(int s[]) | |
{ | |
printf("%7d. ", s[0]); | |
for (i = 1; i < L1; i++) | |
printf("%08d ", s[i]); | |
printf("\n"); | |
} | |
/* | |
* メイン処理 | |
*/ | |
int main() | |
{ | |
try | |
{ | |
// 計算クラスインスタンス化 | |
Calc objCalc; | |
// ネイピア数計算 | |
objCalc.calc(); | |
} | |
catch (...) { | |
cout << "例外発生!" << endl; | |
return -1; | |
} | |
// 正常終了 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment