+ 1

# pl give code to enter a number and check if it is prime or composite

5 Antworten

+ 2

the simpliest way to check if 'n' is prime is something like this:
bool Prime(int n)
{
for (int i= 2; i<= Math.Sqrt(n); i++)
{
if (n%i == 0)
return false;
}
return true;
}
This methode returns true if 'n' is prime and false otherwise. This algorithm simply check if any integer number from 2 to Sqrt(n) divide n without the remainder. In other words, if 'n' has dividers except 1 and itself.
And we use Sqrt(n) because when we reach Sqrt(n) the divisors just "switches".
Let's say you have 100: 100 = 50*2 = 25*4= 20*5 = 10*10 = 5*20 = 25*4 = 50*2 = 100. The dividers from one and another side of the '10*10' are the same, but just switched.
This code is simpliest, but the slowest at the same time. If you want to do it faster, you should look into "Fermat test" and others.

0

Please look through previous questions, I wrote an answer to the same question some time ago

0

thanks

0

If a number is 2,3,5, or 7, it is a Prime.
If a number is greater than 7 and is divisible by 2, 3, 5 or 7 it is Composite.
If a number is greater than 7 and is not divisible by 2, 3, 5 or 7 it is Prime.

- 4

Juat use any king of if statement and teat if it divides by two and has no ramainder
6%2=0 so its prime