Advertisement
Garey

Armstrong Number

Mar 6th, 2018
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. int armstrong_method(int, size_t);
  7.  
  8. int main() {
  9.     int n;
  10.  
  11.     try {
  12.         cout << "Vuvedi n: ";
  13.         cin >> n;
  14.  
  15.         if (!cin || n < 2) {
  16.             throw "Error: Invalid number";
  17.         }
  18.        
  19.         size_t count((size_t)log10((double)n) + 1);
  20.  
  21.         if (armstrong_method(n, count) == n)
  22.             cout << "Armstrong number: " << armstrong_method(n, count) << endl;
  23.         else
  24.             cout << "Not an Armstrong number, but here is the sum: " << armstrong_method(n, count) << endl;
  25.  
  26.     }
  27.     catch (const exception &error) {
  28.         cout << error.what();
  29.     }
  30.  
  31.     return 0;
  32. }
  33.  
  34. int armstrong_method(int n, size_t power) { return n ? (pow(n % 10, power) + armstrong_method(n / 10, power)) : 0; }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement