How to make a program to determine if an integer is prime or not? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to make a program to determine if an integer is prime or not?

Hello everybody, I have to make a program to determine if a supplied integer is prime or not. At the same time it has to be within the range of 1 and 999, otherwise it will ask the user to enter a number within that range. It should also not be considered in case 1 is entered as a prime number. I have tried to do it but it always gives me an error that I do not understand where it comes from. Could you explain to me where I fail, The program I did so far: #include <stdio.h> int main () { int num, cont = 0, div = 1; printf ("enter a number"); scanf ("% d", &num); while (num> = 1 && num <= 999) { if (num% div == 0) { cont ++; } div ++; } if (cont == 2) { printf ("The number is prime"); } return 0; }

18th May 2021, 10:24 PM
Brian Ayvar
Brian Ayvar - avatar
3 Answers
0
Brian Ayvar Here's an efficient prime generator (especially when dealing with large numbers): int is_prime(int a) { if (a == 2) return 1; if (a < 2 || !(a & 1)) return 0; int l = a / 3; for (int i=3;i<=l;i+=2) { if (!(a % i)) return 0; } return 1; } // Hope this helps
19th May 2021, 6:39 AM
Calvin Thomas
Calvin Thomas - avatar
0
You need to be really careful about spaces . Compare the following two lines with yours. scanf ("%d", &num); while (num >= 1 && num <= 999) { There should be no space between % and d here, otherwise it can change the whole meaning of what type of data compiler expects . It should be >= not > = . Again no spaces .
18th May 2021, 11:00 PM
Abhay
Abhay - avatar
0
hey Brian Ayvar take loop from 2 (say counter) to less than number , see that counter completely divides that number or not , if it divides that mean that's not prime , exit ! >>>you can make efficient by taking loop from 2 to " half of number " !
19th May 2021, 1:35 AM
Giriraj Yalpalwar
Giriraj Yalpalwar - avatar