I have created a function to identify if a number is prime or not. I need to then use the return value ( it's a boolian statement ) in my main program. How to I get my main program to recognize my return? Lets say for simplicity, I just want a cout statement saying "is prime" or "is not prime" in my main program not included in the function. I'm already using the "cin" from my main function as the input so all my files are in order. Thanks in advance My function below.
|
|
|
V
Your prime function is going to run verrrry slow for large numbers. You should check if it is divisible by 2 first then start your for loop at 3 and increment by 2. This will cut the iterations in half. You could also make it so every 3rd increment it will increment an additional 2 which would cut off a third more. Which would make it 1/3 overall iterations compared to the starting. So instead of o(n) it is now o( n /3 ) Another way to cut it even more would be to loop till a sqrt of the value. so now it would be o( ( n / 3 )^ .5 ) ~ o( n / 5 )
here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13
if( value % 2 == 0 ) return( false );
int count = 0;
for( int i = 3; i < sqrt(value); i += 2; )
{
++count;
if( count == 3 )
{
count = 0;
i += 2;
}
if( value % i == 0 ) return( false );
}
return( true );
Wow, a lot of responses. I appreciate the help, I really do. This is for a college assignment. I don't think it will be scrutinized just checked for functionality. What I have to do is insert this function into my main, then I have to display each prime number passed my original input up to 160 prime numbers. Not sure if the "if else" statements in "main" will work well for this.
Lol, not so much. I keep getting errors,
When it runs through the program I get either a 1 or a 0,
I need to keep the original number so I can use a post increment on it in a loop to keep getting prime numbers. Not sure how to do it. I tried creating another variable then assigning it to the original variable after it runs through the program, but that's not working either. I'm sure I could look this up on google but that would be cheating, I plan on doing this for a living one day so I have to work through it. However, my professor is less than informative...
Also if I give the bool expression the value of true it breaks the loop. If only a false the program will continue with the numbers
It's probably something stupid but I can't seem to get it to reassign nums value to number it just runs through the loop using the original value, unless the original value is not prime, then it increments it by one and uses that value 160 times.
So I decided to heck with the nonsense and put everything on one cpp. Everything now works as it should...HOWEVER....I have now run into a problem with the number two, for some reason I can't seem to get it to work if the user enters in "2" for the Number.