CPP Homework 06 20221028
CPP Homework 06 20221028
5.29 (Prime Numbers) An integer is said to be prime if it’s divisible by only 1 and
itself. For example,
2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not.
a) Write a function that determines whether a number is prime.
b) Use this function in a program that determines and prints all the prime numbers
between
2 and 10,000. How many of these numbers do you really have to test before being
sure that you’ve found all the primes?
c) Initially, you might think that n/2 is the upper limit for which you must test to see
whether a number is prime, but you need only go as high as the square root of n.
Why?
Rewrite the program, and run it both ways. Estimate the performance improvement.
ANS: If a number n has two factors a and b, then one must be less than the square
root of
n and one must be greater. Therefore, if n is not prime it will have at least one factor
less than the square root of n, and we only need to check that far. The performance
improvement is roughly a factor of ten, though the running times are so small they
are difficult to measure.
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
...
9739 9743 9749 9767 9769 9781 9787 9791 9803 9811
9817 9829 9833 9839 9851 9857 9859 9871 9883 9887
? 500
? 250
? 375
? 438
? 405
? 380
? 393
? 399
? 396
? 398
? 397