Advertisement
DatProgrammer

P22467

Oct 19th, 2015
511
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int sum_digits(int n) {
  5.  
  6.   int r = 0;
  7.   while (n > 0) {
  8.    
  9.     r = r + (n%10);
  10.     n = n/10;
  11.   }
  12.   return r;
  13. }
  14.  
  15. int count_digits(int n) {
  16.  
  17.   int r = 0;
  18.   int dig = 0;
  19.   while (n > 0) {
  20.    
  21.     r = r + (n%10);
  22.     n = n/10;
  23.     dig++;
  24.   }
  25.   return dig;
  26. }
  27.  
  28. bool prime(int a) {
  29.  
  30.     if (a <= 1) return false;
  31.     for (int i = 2; i*i <= a; ++i) {
  32.         if (a%i == 0) return false;
  33.     }
  34.     return true;
  35. }
  36.  
  37. bool is_perfect_prime (int n) {
  38.  
  39.   if (not prime(n)) return false;
  40.   int sd = sum_digits(n);
  41.   int cd = count_digits(n);
  42.   bool z = prime(sd); //chek if the sum of the digits is prime
  43.   if (z and cd == 1) return true;
  44.   else if (z) return is_perfect_prime(sd); //recursion: if the number of digits is not 1
  45.                        //repeat the process for the sum of digits
  46.   else return false;
  47.  
  48. }
  49.  
  50. int main() {
  51.  
  52.   int n;
  53.   while (cin >> n) {
  54.     if (is_perfect_prime(n) == true) cout << "true" << endl;
  55.     if (is_perfect_prime(n) == false) cout << "false" << endl;
  56.   }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement