- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extended Midy's theorem in C++
Midy’s Theorem is a statement used for decimal expansion of numbers denoted by n/p, where n is any number and p is a prime number and a/p has a repeating decimal with even period.
In Extended Midy’s Theorem, the repeating portion is divided into m digits, then their sum is a multiple of 10m - 1.
Program to illustrate Extended Midy’s Theorem:
Example
#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; }
Output −
Repeating decimal = 0588235294117647 588 2352 9411 7647 Extended Midy's theorem holds!
Advertisements
To Continue Learning Please Login
Login with Google