garryhtreez

6.28

Dec 13th, 2020
540
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. /*6.28
  2. Deitel & Deitel C++ How to Program, 10th ed(Indian subcontinent adaptation)
  3. Visual Studio Community 2019
  4. */
  5.  
  6. #include <iostream>
  7. #include <cmath>
  8. using namespace std;
  9.  
  10. bool isDudeney(unsigned long testNum, unsigned long cubed) {
  11.    unsigned long sum{ 0 };
  12.    int digit{ 0 };
  13.    for (unsigned long divisor = 1'000'000'000; divisor >= 10; divisor /= 10) {
  14.      if (testNum >= divisor) {
  15.         sum += testNum / divisor;
  16.      }
  17.      testNum %= divisor;
  18.   }
  19.   sum += testNum; // at this point testNum should be the digit in the one's position
  20.    if (sum == cubed) return true;
  21.    else return false;
  22. }
  23.  
  24. int main() {
  25.    unsigned long testnum;
  26.    int dudeneyCtr{ 0 };
  27.    unsigned long cubedroot;
  28.  
  29.    // check up to 100 million
  30.    for (testnum = 0; testnum < 100'000'000; testnum++) {
  31.       if (testnum > 0 && testnum % 10'000'000 == 0) cout << testnum << endl; // give some feedback
  32.  
  33.       cubedroot = cbrt(testnum);
  34.       if (cubedroot * cubedroot * cubedroot == testnum) {
  35.          if (isDudeney(testnum, cubedroot)) {
  36.             cout << testnum << " is a Dudeney. Its cube root is " << cubedroot << endl;
  37.             dudeneyCtr++;
  38.          }
  39.       }
  40.    }
  41.    cout << endl << "Count of Dudeney numbers: " << dudeneyCtr << endl;
  42.    return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment