# Design an algorithm (and provide the c code) to accept a number from the user and check if it is a prime number or not?

+1 vote
42 views
Design an algorithm (and provide the c code) to accept a number from the user and check if it is a prime number or not?
posted Aug 28, 2017

+1 vote

A number if prime if it is not divisible by other then 1 and self. So it means if given number is N and if we check from 2 to n-1 if number if not divisible by anyone then its prime. In practice if we do the same from 2 to n/2 then the above logic is suffice.

See the sample code -

``````#include <stdio.h>
#include <stdlib.h>

void main()
{
int n, i, isprime;

printf("Enter a number \n");
scanf("%d", &n);

if (n <= 1)
{
printf("%d is not a prime numbers \n", n);
exit(1);
}
isprime = 1;
for (i = 2; i <= n / 2; i++)
{
if ((n % i) == 0)
{
isprime = 0;
break;
}
}

if (isprime == 1)
printf("%d is a prime number \n", n);
else
printf("%d is not a prime number \n", n);
}
``````
Similar Questions
–1 vote

Write a C program to check if the given string is repeated substring or not.
ex
1: abcabcabc - yes (as abc is repeated.)
2: abcdabababababab - no

Can we consider `"a car a man a maraca"` as palindrome string?
Are they really a palindrome?

Sorry for hiding my identity :)

Example :
Let the list be {2,3,5} and Assume always 1 be included then

2th number is 2
3th number is 3
4th number is 4
5th number is 5
6th number is 6
7th number is 8
8th number is 9
9th number is 10
10th number is 12
11th number is 15 and so on...