Discrete Mathematics and Its Applications, Seventh Edition

Published by McGraw-Hill Education
ISBN 10: 0073383090
ISBN 13: 978-0-07338-309-5

Chapter 4 - Section 4.3 - Primes and Greatest Common Divisors - Exercises - Page 272: 7

Answer

function isPrime(n): if n <= 1: return false else if n % 2 == 0: return false else if n == 2: return true else: divisor = 3 while divisor * divisor <= n: if n % divisor == 0: return false divisor += 2 return true

Work Step by Step

1- Start with a function isPrime that takes an integer n as input and returns a boolean value. 2- If n is less than or equal to 1, return false since 1 and 0 are not prime. 3- If n is divisible by 2 (n modulo 2 = 0), return false since even numbers greater than 2 are not prime. 4- If n is equal to 2, return true since 2 is prime. 5- Initialize a variable divisor to 3. 6- While divisor squared is less than or equal to n, do the following steps: -If n is divisible by divisor (i.e., n modulo divisor is equal to 0), return false since n is not prime. -Increment divisor by 2 to check the next potential divisor. This is because even divisors have already been checked in step 3, so we only need to consider odd divisors. 7-If the loop completes without finding any divisors, return true since n is prime.
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.