Day 8 - Assignment Answers
Day 8 - Assignment Answers
If it is, we print that the number is not prime and exit the loop using
the break statement. If the loop completes without finding a
divisor, we print that the number is prime using the else clause that
is executed after the loop completes successfully.
Suppose we have a number num that is not prime. Then there must be two factors
of num, say a and b, such that num = a * b. One of a and b must be less than or equal
to the square root of num, and the other must be greater than or equal to the
square root of num. Otherwise, their product would be greater than num.
For example, suppose num = 24. The factors of num are 1, 2, 3, 4, 6, 8, 12, 24. Notice
that the largest factor less than or equal to the square root of num (which is
4.89897948557...) is 4, and the smallest factor greater than or equal to the square
root of num is 6. So if we check all the factors of num up to 4, we can be sure that if
none of them divide num evenly, then num is not prime.
Therefore, we only need to check for factors of num up to the square root of num.
This reduces the number of computations required and makes the algorithm more
efficient.
The function then iterates through each number in that range, checking
whether it is prime or not.
If the number is divisible by any of those numbers, it is not prime, and the
loop exits using the break statement.
If the loop completes without finding a divisor, the number is prime, and it
is printed to the console using the print statement.