Write C++ program to print perfect numbers between given interval using function


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. int isPerfect(int num);
  6. void printPerfect(int start, int end);
  7.  
  8.  
  9.  
  10. int main()
  11. {
  12. int start, end;
  13.  
  14. // Inputting lower and upper limit to print perfect numbers
  15. cout<<"Enter lower limit to print perfect numbers: ";
  16. cin>>start;
  17. cout<<"Enter upper limit to print perfect numbers: ";
  18. cin>>end;
  19.  
  20. cout<<"All perfect numbers between "<<start<< " to "<<end <<" are: "<<endl;
  21. printPerfect(start, end);
  22.  
  23. return 0;
  24. }
  25.  
  26. int isPerfect(int num)
  27. {
  28. int i, sum;
  29.  
  30. // Finding sum of all proper divisors
  31. sum = 0;
  32. for(i=1; i<num; i++)
  33. {
  34. if(num % i == 0)
  35. {
  36. sum += i;
  37. }
  38. }
  39.  
  40. /*
  41.   If sum of proper positive divisors equals to given number
  42.   then the number is perfect number
  43.   */
  44. if(sum == num)
  45. return 1;
  46. else
  47. return 0;
  48. }
  49.  
  50. //Printing all perfect numbers
  51. void printPerfect(int start, int end)
  52. {
  53. // Iterating from start to end
  54. while(start <= end)
  55. {
  56. if(isPerfect(start))
  57. {
  58. cout<<start<<endl;
  59. }
  60.  
  61. start++;
  62. }
  63. }
  64.  
  65.  

Result

C++ language techstudy.org

     





Related Topics




Popular Posts