Logic:
- Prime Number A number is prime if it is divisible by 1 and the number itself only.
- Enter the number n
- Example 1: n=15
- We will check whether number is divisible by any number from 2 to n-1 here 14.
- If it is divisible by any number (example 15 is divisible by 3) , then It is not prime number. And We dnt need to check further divisibility from 4 to 14.
- Example 2: n=5
- We will check whether number is divisible by any number from 2 to n-1 here 4.
- Since 5 is not divisible by any numbers 2, 3, 4 . So It is a prime number.
Algorithm
- Enter the number as n
- for(i=2;i<=n-1;i++)
- {
- if(n%i==0)
- {
- printf(“It is not prime”);
- break;
- }
- }
- if(i==n)
- printf(“It is prime”);
Time Complexity: O(n)
Space Complexity: O(1)
Program
#include <stdio.h> char check_prime(int n); int main() { printf("******************************************************\n"); printf("******************************************************\n"); printf("** WAP to check a number for prime using function **\n"); printf("** Created by Sheetal Garg **\n"); printf("** Assistant Professor **\n"); printf("** Phone No:9467863365 **\n"); printf("******************************************************\n"); printf("******************************************************\n"); int n; char result; printf("\nenter number\n"); scanf("%d", &n); result = check_prime(n); if (result == 'T') printf("\nIt is prime"); else printf("\nIt is not Prime"); return 0; } char check_prime(int n) { int i; for (i = 2; i <= n - 1; i++) if (n % i == 0) return 'F'; return 'T'; }
Output 1
****************************************************** ****************************************************** ** WAP to check a number for prime using function ** ** Created by Sheetal Garg ** ** Assistant Professor ** ** Phone No:9467863365 ** ****************************************************** ****************************************************** enter number 5 It is prime
Output 2
****************************************************** ****************************************************** ** WAP to check a number for prime using function ** ** Created by Sheetal Garg ** ** Assistant Professor ** ** Phone No:9467863365 ** ****************************************************** ****************************************************** enter number 15 It is not prime