Problem 24

author
By Supreme2023-03-15
Problem Statement :
Write a program to check whether the given number is prime or not.
Code:

#include <stdio.h>
int main()
{
printf("\t\tPrime Number");
printf("\n=====================================================\n\n");
int n, i, m = 0, flag = 0;
printf("Enter The Number To Check Prime:");
scanf("%d", &n);
m = n / 2;
for (i = 2; i <= m; i++)
{
if (n % i == 0)
{
printf("\n\nNumber is not prime");
flag = 1;
break;
}
}
if (flag == 0)
printf("Number is prime");
return 0;
}

Description :

This program checks whether a given number is prime or not. Here's a breakdown of the code:

  • The program starts by printing a header that says "Prime Number".
  • It then declares some variables: n (the number to be checked), i (a loop counter), m (a variable used to optimize the loop), and flag (a variable that will be used to determine whether the number is prime or not).
  • The program asks the user to enter the number to be checked for prime.
  • It then sets m to be half of n, since no factor of n can be greater than n/2.
  • The program then enters a for loop that starts at 2 and goes up to m. It checks whether each number between 2 and m is a factor of n.
  • If a factor is found, the program prints a message saying that the number is not prime, sets the flag variable to 1, and breaks out of the loop.
  • If no factor is found, the program prints a message saying that the number is prime.
  • Finally, the program returns 0.
Output Image:
Output-image

© Copyright 2022. All right reserved, GTU Coder.