擴充套件 Midy 定理的 C++ 實現
Midy 定理是用來表示數形式為 n/p 的小數展開的定理,其中 n 為任意數,p 為質數,a/p 的小數位重複且週期為偶數。
在擴充套件 Midy 定理中,重複部分被劃分為 m 個數字,然後這些數字的總和是 10m - 1 的倍數。
演示擴充套件 Midy 定理的程式:
示例
#include <bits/stdc++.h>
using namespace std;
string findDecimalValue(int num, int den) {
string res;
unordered_map<int, int> mp;
int rem = num % den;
while ((rem != 0) && (mp.find(rem) == mp.end())) {
mp[rem] = res.length();
rem = rem * 10;
int part = rem / den;
res += to_string(part);
rem = rem % den;
}
return (rem == 0) ? "-1" : res.substr(mp[rem]);
}
bool isPrime(int n) {
for (int i = 2; i <= n / 2; i++)
if (n % i == 0)
return false;
return true;
}
void ExtendedMidysAlgo(string str, int n, int m) {
if (!isPrime(n)) {
cout<<"Denominator is not prime, thus Extended Midy's theorem is not applicable";
return;
}
int l = str.length();
int part1 = 0, part2 = 0;
if (l % 2 == 0 && l % m == 0) {
int part[m] = { 0 }, sum = 0, res = 0;
for (int i = 0; i < l; i++) {
int var = i / m;
part[var] = part[var] * 10 + (str[i] - '0');
}
for (int i = 0; i < m; i++) {
sum = sum + part[i];
cout << part[i] << " ";
}
cout << endl;
res = pow(10, m) - 1;
if (sum % res == 0)
cout << "Extended Midy's theorem holds!";
else
cout << "Extended Midy's theorem doesn't hold!";
}
else if (l % 2 != 0) {
cout << "The repeating decimal is of odd length thus Extended Midy's theorem is not applicable";
}
else if (l % m != 0) {
cout<<" The repeating decimal can not be divided into m digits";
}
}
// Driver code
int main()
{
int numr = 1, denr = 17, m = 4;
string res = findDecimalValue(numr, denr);
if (res == "-1")
cout << "The fraction does not have repeating decimal";
else {
cout << "Repeating decimal = " << res << endl;
ExtendedMidysAlgo(res, denr, m);
}
return 0;
}輸出 −
Repeating decimal = 0588235294117647 588 2352 9411 7647 Extended Midy's theorem holds!
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP