pl give code to enter a number and check if it is prime or composite | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

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

31st Aug 2016, 4:52 PM
Rachana Kumar
Rachana Kumar - avatar
5 Answers
+ 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.
31st Aug 2016, 7:39 PM
shir
shir - avatar
0
Please look through previous questions, I wrote an answer to the same question some time ago
31st Aug 2016, 6:50 PM
Tomek Cymes
Tomek Cymes - avatar
0
thanks
1st Sep 2016, 4:33 PM
Rachana Kumar
Rachana Kumar - avatar
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.
2nd Sep 2016, 7:52 PM
Erwin Mesias
Erwin Mesias - avatar
- 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
1st Sep 2016, 10:22 AM
Bryce Johnson
Bryce Johnson - avatar