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
1
u/clockworm Jun 26 '14
hey thanks for the reply! your examples are in line with what i was thinking. the book i am using (Without Fear by Brian Overland), asked me to optimize the code to calculate the sqrt of n only once before the loop and then using the found divisor in the loop.
my problem is in understanding what exactly he's asking for that's different than what i've done other than using the new variable. he wants me to use the double float var to facilitate large numbers. i think i'm just trying each possible divisor from 2 to sqrt(n), instead of stopping at the first one and then plopping it into my loop. your 2nd example is interesting and i hadn't thought of it that way. i hope i'm not overthinking this.