Header Ads

Check Prime or Armstrong Number

Check Prime and Armstrong Number

In this program, two user-defined functions check_Prime_Number() and check_Armstrong_Number() are created.
The check_Prime_Number() returns 1 if the number entered by the user is a prime number. Similarly, check_Armstrong_Number() returns 1 if the number entered by the user is an Armstrong number.



#include <stdio.h>
#include <math.h> // using maths librery
int check_Prime_Number(int number);
int check_Armstrong_Number(int number);
int main()
{
    int number, flag;
    printf("Enter a positive integer: ");
    scanf("%d", &number);
    // Check prime number
    flag = check_Prime_Number(number);
    if (flag == 1)
        printf("%d is a prime number.\n", number);
    else
        printf("%d is not a prime number.\n", number);
    // Check Armstrong number
    flag = check_Armstrong_Number(number);
    if (flag == 1)
        printf("%d is an Armstrong number.",number);
    else
        printf("%d is not an Armstrong number.",number);
    return 0;
}

int check_Prime_Number(int number)
{
    int i, flag = 1;
    for(i=2; i<=n/2; ++i)
    {
    // condition for non-prime number
        if(n%i == 0)
        {
            flag = 0;
            break;
        }
    }
    return flag;
}

int check_Armstrong_Number(int number)
{
    int originalNumber, remainder, result = 0, n = 0, flag;
    originalNumber = number;
    while (originalNumber != 0)
    {
        originalNumber /= 10;
        ++n;
    }
    originalNumber = number;
    while (originalNumber != 0)
    {
        remainder = originalNumber%10;
        result += pow(remainder, n);
        originalNumber /= 10;
    }
    // condition for Armstrong number
    if(result == number)
        flag = 1;
    else
        flag = 0;
    return flag;
}
Output:
Enter a positive integer: 407
407 is not a prime number.
407 is an Armstrong number.


Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Powered by Blogger.