PLEASE DO NOT SOLVE THE PUZZLE FOR ME, NOR TELL ME WHETHER THIS PROGRAM WILL WORK OR NOT
I am trying to make a program that sums all the prime numbers under two million. To do this, I tried to make a function to decide whether or not the number is prime. Once again, please do not tell me whether it will work or not, this is simply a compiler issue.
Also, even if you use the same names for formal and actual parameters, they're still different.
So for example, you can use another name instead of testThis and it will still work without changing main().
Your problem comes from forgetting the function parameter on line 14. And...
You should initialize total to 0 first.
When testing for primes, testing until the square root is enough.
Don't start the test from 1, because that will always return true.
What Mats said.
(Also, == true is redundant)
When isItPrime returns true, your code is going to say "if(true ==true)".
Anyway, you forgot the parentheses and the function parameter @line 11, it should be isItPrime(testThis)
It really isn't redundant, it's more just a matter of style. It will compile to the same code no matter if == true is there or not.
Personally, I like to write it out like that, because it is easier to see than looking for the presence of a !, as in: if (!isSafe()) vs if (!sSafe() == false)
Also, while I am at it, any comments on my coding form/readability are welcome! I know I do not put in comments, but I intend to start once I learn to comment properly (textbook gets to it soon).
#include <vector> //Why is this included when you are not using it?
#include <iostream>
#include <cmath> //Why is this included when you are not using it?
bool isItPrime(long testThis);
int main() {
long testThis;
long total;
while(testThis < 2000000) {
if (isItPrime(testThis) == true) {++total;} //This is a comment
}
}
/*
This is a multi-line
comment
block
*/
//This is just for one line.
bool isItPrime() {
for(int i=1; i==(i/2 + 1); ++i){
if(testThis%i==0) {returnfalse;}
}
returntrue;
}
/**********************************
* This is a very common way of
* making multi-line comments
* look very impressive.
**********************************/
Ah, I should clarify. I know how to comment, I just don't know how to make comments understandable for the reader, so with these simpler programs I don't bother.
I saw this post the other day and wanted to chime in - it looks like this is Project Euler Problem # 10, right? I solved that one over the summer and would be happy to show you my code to see how we compare when you've solved the problem to your satisfaction :) (I am also new to code, so I went through the Project Euler problems as a fun side project.)