+ 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
4 odpowiedzi
+ 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;
}
+ 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 : )
+ 2
You could have searched all codes, I made this one some days ago:
https://code.sololearn.com/c852vsjvBgX1/?ref=app