Write C++ program to print all strong numbers between 2 numbers


I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Function declarations
  5. long long fact(int num);
  6. void printStrongNumbers(int start, int end);
  7.  
  8.  
  9. int main()
  10. {
  11. int start, end;
  12.  
  13. /* Input start and end range */
  14. cout<<"Enter the lower limit: ";
  15. cin>>start;
  16. cout<<"Enter the upper limit: ";
  17. cin>>end;
  18.  
  19. cout<<"List of strong numbers between"<<start<<"to "<<end << " are: "<<endl;
  20. printStrongNumbers(start, end);
  21.  
  22. return 0;
  23. }
  24.  
  25.  
  26.  
  27. //Printing all strong numbers in a given range
  28. void printStrongNumbers(int start, int end)
  29. {
  30. long long sum;
  31. int num;
  32.  
  33. // Iterates from start to end
  34. while(start != end)
  35. {
  36. sum = 0;
  37. num = start;
  38.  
  39. // Calculating sum of factorial of digits
  40. while(num != 0)
  41. {
  42. sum += fact(num % 10);
  43. num /= 10;
  44. }
  45.  
  46. // If sum of factorial of digits equal to current number
  47. if(start == sum)
  48. {
  49. cout<<start<<endl;
  50. }
  51.  
  52. start++;
  53. }
  54. }
  55.  
  56. //Recursively find factorial of any number
  57. long long fact(int num)
  58. {
  59. if(num == 0)
  60. return 1;
  61. else
  62. return (num * fact(num-1));
  63. }
  64.  

Result

C++ language techstudy.org

     





Related Topics




Popular Posts