Question

C language int is_prime(int n) { if (n <= 1) return 0; if (n % 2...

C language

int is_prime(int n)
{
if (n <= 1) return 0;
if (n % 2 == 0 && n > 2) return 0;
for (int i = 3; i < n / 2; i += 2)
if (n % i == 0)
return 0;

return 1;
}

What do the three lines in this function mean?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Given function actually finds whether given integer is a positive prime number or not, if its apositive prime number it returns 1 and 0 otherwise.

first line [if (n <= 1)] checks whether given integer is less than 1 then it returns 0.

second line [if(n%2==0 && n>2)] checks for even number greater than 2 and returns 0 for those even numbers.

Now consider the bold 3 lines of code:

for loop starts with value of i=3, each iteration it increments i by 2 until n/2.

i.e. i values are 3,5,7,...n/2

In each iteration it checks whether given number divides i, so its not prime and returns 0.

Now after termination of for loop all cases to check nnot prime is over so the number is prime and returns 1.

Add a comment
Know the answer?
Add Answer to:
C language int is_prime(int n) { if (n <= 1) return 0; if (n % 2...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT