exercise i dont quite understand

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <cmath>
using namespace std;



int main(){

	int n, i, is_prime = true;

	cout << "Enter a number and press ENTER: ";
    cin >> n;
	double m = sqrt((double)n);

	i = 2;
	while(i <= sqrt((double)n)){
		if (n % i == 0){
			is_prime = false;
			break;
		}
		i++;
	}

	if(is_prime)
		cout << "Number is prime." << endl;
	else
		cout << "Number is not prime." << endl;
		
system("pause");
return 0;}



Exercise 2.4.1. Optimize the program by calculating the square root of n just once,
rather than over and over. You’ll need to declare another variable and set it to the
square root of n. The type should be double. You can then use this variable in the
while condition.


my question is:

if they want me to identify if its a prime number or not a prime number with just one calculation, then it would be impossible right?
i wouldnt get the correct answer wether its prime or not when i enter a random number.

my second question:

how should i use the variable m s condition?
i have been trying to but i always end up with errors :(
cant think of a way to solve this exercise feels like im lways misunderstanding exercises
closed account (Gz64jE8b)
1
2
3
4
5
	while(i <= sqrt((double)n)){
		if (n % i == 0){
			is_prime = false;
			break;
		}


You're calculating the square root of n every time the while() runs.

You've already assigned the square root of n to m.

'Optimizing' the program would be this:

while(i <= m){
if (n % i == 0){
is_prime = false;
break;
}

This way every time the while() runs it's not calculating the square root of n then checking it.

The square root of n is already stored in m so it just has to check the value rather than calculate it and then check it.

Edit: Just compiled this and tested (with my 'fix') :
Enter a number and press ENTER: 4
Number is not prime.

Enter a number and press ENTER: 7
Number is prime.

P.S when 1 or 0 is entered it returns it as prime, math states 1 and 0 aren't prime. You should fix this and hope for extra credit.
Last edited on
thank you soooooooo so so so so sooooooooo much!

now i see! i thought they meant running the loop only one time and then break out of the loop.

thank you once again!!!
Topic archived. No new replies allowed.