+ 1

How to define a function which returns True for prime numbers?

I am unable to figure out that how can I define a function which returns true if a prime number is given as an argument and false for non prime number. Please make me understand the logic behind it. I prefer it to be in python or C

27th Aug 2018, 5:32 AM
Anaadi Dubey
Anaadi Dubey - avatar
4 Réponses
+ 3
Example in Python: def IsPrime(num): limit = (num // 2) + 1 for i in range(2, limit): if num % i == 0: return False return True num = int(input("Enter positive integer: ")) print(num) print("{} is a prime number".format(num) if IsPrime(num) else "{} is not a prime number".format(num)) Example in C: #include <stdio.h> int is_prime(int n) { int limit = n / 2; for(int i = 2; i <= limit; ++i) { // Checking for prime number if(n % i == 0) return 0;// false, non prime } return 1; // true (prime) } int main() { int num = 0; printf("Enter a positive integer: "); scanf("%d", &num); if(num >= 2) { printf("%d\n", num); if (is_prime(num)) printf("%d is a prime number\n", num); else printf("%d is not a prime number\n", num); } return 0; }
27th Aug 2018, 6:44 AM
Ipang
+ 2
In which language are you doing this? may I suggest to add the language for question's tag? just for the sake of clarity : )
27th Aug 2018, 5:41 AM
Ipang
+ 2
You could have searched all codes, I made this one some days ago: https://code.sololearn.com/c852vsjvBgX1/?ref=app
27th Aug 2018, 8:56 AM
Paul
Paul - avatar
+ 1
"In which language are you doing this? may I suggest to add the language for question's tag? just for the sake of clarity : )" Ipang I prefer Python but C will also work fine with me
27th Aug 2018, 5:44 AM
Anaadi Dubey
Anaadi Dubey - avatar