Let me tell you what I really hate programming, for real...Really hate it. But if you wanna create a video game or gain access to video gaming industry, you must know or have some decent programming skills. No choice.Code:#include <iostream> #include <math.h> using namespace std; int main() { // Declare four variables n, i, an, and is_prime respectively. int n; // Number to test for primeness int i; // Loop counter int is_prime; // Assuming that the number is prime until proven otherwise is_prime = true; // Prompt user input cout << "Please enter a number for the primeness number test: "; cin >> n; // Test for prime-ness by checking for divisibility // by all whole numbers from 2 to sqrt(n) i = 2; while(i <= sqrt(static_cast<double>(n))){ if(n % i == 0){ is_prime = false; i++; } } if(is_prime){ cout << "The number is prime." << endl; }else{ cout << "The number is not prime."; } return 0; }

Anyway, here is the exercise question

2.4.1 Optimize the program further by calculating the square root of n just once rather than over and over as was done in the example. To perform this optimization, you will need to declare another variable and set it to the square root of n. The type should be double. Write a complete program that includes this optimization.

Well...I have found this kinda confusing and for my level of computer programming, it is hard for me to do it. Since while loop is for repetition, unless you use for loop or other methods, there is no way, in my opinion, to calculate the square root once with the use of while loop...I really need help here.

The loop executed without problems, but it didn't work the way I want it to be. Besides, the input of user doesn't function at all.Code:#include <iostream> #include <math.h> using namespace std; int main() { // Declare four variables n, i, an, and is_prime respectively. int n; // Number to test for primeness int i; // Loop counter double an; // Optimization int is_prime; // Assuming that the number is prime until proven otherwise is_prime = true; // Prompt user input cout << "Please enter a number for the primeness number test: "; cin >> n; // Test for prime-ness by checking for divisibility // by all whole numbers from 2 to sqrt(n) i = 2; an = n; while(i <= sqrt(static_cast<double>(n))){ if(n % i == 0){ is_prime = false; i++; } } if(is_prime){ cout << "The number is prime." << endl; }else{ cout << "The number is not prime."; } return 0; }