this is an example code from the book:
Code:
#include <iostream>
#include <math.h>
using namespace std;
main()
{
int n;
int i;
int is_prime;
is_prime = true;
cout<< "Please enter a number: ";
cin>> n;
i = 2;
while(i <= sqrt(static_cast<double>(n))){
if(n % i == 0){
is_prime = false;
break;
}
i++;
}
if(is_prime)
cout<< "Your number is prime";
else
cout<< "Your number is not prime";
return 0;
}
Howerver, in the exercise, it just tells you that you have to optimize it. I have been thinking for couple hours but still find no answer.
This is the question: 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 need to declare another variable and set it to the square root of n. The type should be double.
Would you please just tell me how and explain in details why?