Help me understand.

This is a discussion on Help me understand. within the C++ Programming forums, part of the General Programming Boards category; Code:
// This is the main project file for VC++ application project
// generated using an Application Wizard.
#include "stdafx.h"
...

I wrote this program using recursion. I know what I did for the most part, but I am not clear on when it returns true. The program runs alright and does what its supposed to do. But I didnt set any boundary on k so I am wondering when it breaks out and returns true. If k didnt break then the program wouldnt display the correct answer. Does it break when k =nv? If so, why? Thanks for the help.

The program will return true, if it fails the first two tests for being not evenly divisible by two and not evenly divisible by three.

Also, you might want to re-check this part of the code. Just by running the program and everything seems fine, you might be lead into believing that recursive calls are being made, but this is not the case... because the call to return will break out of the function before the next function call will take place:

Code:

if (nv %k ==0){
return false; //The function will stop at this point
checkprime(nv, k+1); // This function will never be called.
}

Apart from the points made above, you should also double check your programs logic. If someone enters a prime number bigger than 2 (eg. 3) it will return false. In fact, this function (without the errors pointed out already) will return false for every number entered, because eventually k will become the same value as nv, and nv % k == nv % nv == 0, so you need to make sure that you stop looping/recursing when hit the number that is one below nv.

As a side note, you don't need to check for nv % 2 every time you call the function, this is one of the inefficiencies that I'm sure CornedBee was referring to.

A small suggestion, instead of starting from k = 3 and go upwards, why not start at k = n - 1 and stop when you get to 2?

And as a big suggestion, do some reading up on the Sieve of Eratosthenes, it might just help you find a faster solution