Program to Check Whether a Number is Prime or Armstrong in C
Prime Number & Armstrong Number :
Prime Number is defined as the number which is divisible by itself and by one only. It should not be divisible by any other number while armstrong number is defined as the number when sum of the cube of the individual digits is equal to the given value.
Working of Program :
In the program, we will take a value and write two function to check whether a number is prime or armstrong number.
#include<stdio.h> // function to check number is prie or not int prime_check(int n){ for(int i=2;i*i < n; i++){ if(n%i==0) return 0; } return 1; } // function to check number is armstrong or not int armstrong_check(int n){ int temp, sum=0, r; for(temp=n;n!=0;n=n/10){ r=n % 10; sum=sum+(r*r*r); } if(sum==temp) return 1; else return 0; } int main() { int val = 17; if(prime_check(val)==1){ printf("%d number is prime\n", val); } else{ printf("%d is not prime\n ",val); } if(armstrong_check(val)==1){ printf("%d number is armstrong\n", val); } else{ printf("%d number is not armstrong\n", val); } return 0; }
Output :
17 number is prime 17 number is not armstrong
Example :
Let’s solve the same problem by using the recursive function to check number whether prime or armstrong instead of iterative functions.
#include<stdio.h> #include<math.h> // recursive function to check number is prie or not int prime_check(int i, int n){ if(n==i) return 0; else if(n%i==0) return 1; else return prime_check(i+1,n); } // recursive function to check number is armstrong or not int armstrong_check(int n){ if(n>0) return (pow(n%10,3) + armstrong_check(n/10)); } int main() { int val = 17; if(prime_check(2,val)==0){ printf("%d number is prime\n", val); } else{ printf("%d is not prime\n ",val); } if(armstrong_check(val)==val){ printf("%d number is armstrong\n", val); } else{ printf("%d number is not armstrong\n", val); } return 0; }
Output :
17 number is prime 17 number is not armstrong
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment