Question
Example 4.2.1. Revise Example 4.2 to make it more optimal. When you consider the speed of todays microprocessors, its unlikely youll see a difference in
Example 4.2.1. Revise Example 4.2 to make it more optimal. When you consider the speed of todays microprocessors, its unlikely youll see a difference in exe- cution, although if you attempt to test an extremely large number, say, more than a billion, you might see a difference. (By the way, good luck in finding a prime number in that range, if youre just looking for one by chance. Prime numbers become rarer as you get into larger values.) In any case, the following changes to code make the program more efficient for large numbers: ? Calculate the square root of n only once by declaring a variable square_root_ of_n and determining its value before entering the for loop. This variable should be a double variable. ? Once a divisor of n is found, you dont need to look for any more divisors. Therefore, in the if statement inside the loop, add a break statement (breaking out of the loop) after setting is_prime to false. Can the answer be in c++ language?
Chapter 4 The Handy, All-Purpose "for" Statement prime2.cpp #include
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started