r/programminghomework • u/clockworm • Jun 25 '14
determining primeness in c++
hey, i hope this subreddit isn't dead. but i just started teaching myself to code. i have written a program to determine if a number is prime by using this loop:
for (int i = 2; i <= sqrt(n); i++){ if (n % i == 0) is_prime = false; }.
how can i rewrite my program to calculate the √n only once by declaring a double var "sqr_rt_n" before the for loop, then using it to determine primeness. i know i need a break; after setting is_prime to false. but how can i get rid of the counter var i, or do I keep it?
i hope this was legible, i'm typing it on my phone. i tried looking online but all the threads have replies with complex code using advanced prime-finding techniques which i'm not using. i know it's probably easy, but i just can't break through. i don't have anyone to show me since i'm alone....forever, forever alone...
thanks for any assistance!
View all comments
Show parent comment
2
u/thediabloman Jun 26 '14
It sounds like the book is looking for the first example. With the piece of come you have so far you will be checking every even number from 2 to sqrt(n), is there a Way to improve on that? Every even number is not necessary after the first check for 2.