扩展 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!

更新日期:22-Jan-2021

93 次浏览

开启你的职业之路

完成课程以获得认证

入门
广告