Write C++ program to check prime and armstrong numbers 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. #include <math.h>
  3. using namespace std;
  4.  
  5. int checkPrimeNumber(int n);
  6. int checkArmstrongNumber(int n);
  7.  
  8. int main(){
  9.  
  10. int num, flag;
  11.  
  12. cout<<"Enter a positive integer: ";
  13. cin>>num;
  14.  
  15. // Checking prime number
  16. flag = checkPrimeNumber(num);
  17. if (flag == 1)
  18. cout<<num<<" is a prime number"<<endl;
  19. else
  20. cout<<num<<" is not a prime number"<<endl;
  21.  
  22. // Checking Armstrong number
  23. flag = checkArmstrongNumber(num);
  24. if (flag == 1)
  25. cout<<num<<" is a Armstrong number"<<endl;
  26. else
  27. cout<<num<<" is a not an Armstrong number"<<endl;
  28. return 0;
  29. }
  30. //function to check prime number
  31. int checkPrimeNumber(int num)
  32. {
  33. int i, flag = 1;
  34.  
  35. for(i=2; i<=num/2; ++i)
  36. {
  37.  
  38. // condition for non-prime number
  39. if(num%i == 0)
  40. {
  41. flag = 0;
  42. break;
  43. }
  44. }
  45. return flag;
  46. }
  47.  
  48. //function to check Armstrong Number
  49. int checkArmstrongNumber(int number)
  50. {
  51. int originalNumber, remainder, result = 0, num = 0, flag;
  52.  
  53. originalNumber = number;
  54.  
  55. while (originalNumber != 0)
  56. {
  57. originalNumber /= 10;
  58. ++num;
  59. }
  60.  
  61. originalNumber = number;
  62.  
  63. while (originalNumber != 0)
  64. {
  65. remainder = originalNumber%10;
  66. result += pow(remainder, num);
  67. originalNumber /= 10;
  68. }
  69.  
  70. // condition for Armstrong number
  71. if(result == number)
  72. flag = 1;
  73. else
  74. flag = 0;
  75.  
  76. return flag;
  77. }
  78.  

Result

C++ language techstudy.org

     





Related Topics




Popular Posts