bool function for prime numbers - c++

I have the following code for checking whether the first 20 positive numbers are prime using a bool function.
#include <iostream>
#include <cmath>
using namespace std;
bool prime(int);
/*
function to evaluate whether a positive integer is prime (true)
or not prime (false)
*/
int main()
{
for(int x=1; x<=20; x++)
{
cout << x << " a prime ? (1 yes, 0 no) "
<< prime(x) << endl;
}
return 0;
}
bool prime(int x)
{
for(int i=2; i<= sqrt(x); i++)
{
if ((x%i) != 0)
return true;
else
return false;
}
}
It works for all numbers 1 to 20 apart from 2 and 3 where the output is 0 instead of 1. I think I know why. For x = 2 and 3 there is no i in the for loop such that i<=sqrt(2) or i<=sqrt(3).
How could I modify the code so it would work for these values too?
Also there is an error message "Control may reach end of non-void function". Why is this?
Thanks.

Modify your prime function to the following
bool prime(int x)
{
if (x < 2) return false;
for(int i=2; i<= sqrt(x); i++) {
if ((x%i) == 0) return false;
}
return true;
}
The Control may reach end of non-void function error message tells you that your prime function does not return in all cases (When you pass 1 to your function, it does not go in the for loop, and so exit without explicitly returning anything, which could lead to undefined-behavior). In general, you want to have a return instruction outside of any conditionnal structure.

You return in the wrong place in your prime function.
bool prime(int x) {
for(int i=2; i<= sqrt(x); i++) {
if ((x%i) == 0)
return false;
}
return true;
}
In your existing function you only test the very first i. The compiler warning refers to how if the loop finishes without returning (although this is easy for us to see it never will), then control will reach the end of prime without returning a value.

Extract return true result from cycle!
bool prime( int _x )
{
double x = sqrt( _x );
for( int i = 2; i <= x; ++i )
if ( !( _x % i ) )
return false;
return true;
}

you can also use this without need to sqrt function , there it is
bool prime (int num){
int i,temp;
for (i=2; i<=num/2) && temp; i++)
if (num%i==0)
temp = 0;
return temp;}

Related

VS Studio bizarre output in C++ (prime number check)?

I have a short program consisting of a function that checks, whether a number is prime or not. However the compiler outputs 127 in VS Studio when I invoke the function for the number 3. I want to ask why is that?
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int k) {
for (int i = 2; i < sqrt(i); i++) {
if (k%i == 0) {
return true;
}
else {
return false;
}
}
}
int main()
{
cout << isPrime(3) << endl;
return 0;
}
As commenters have alluded to, your program has undefined behaviour because isPrime doesn't always return from a function you said. From the C++ standard:
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
Because you have declared isPrime will return a bool, and you don't always return a bool you have undefined behaviour.
Instead, you probably want to iterate all odd numbers up to k, and check if k is divisible by the number, and if so return false (since it won't be a prime). Otherwise, return true at the end.
It might look like this:
bool isPrime(unsigned long k)
{
for (auto i = 3; i * i <= k; i += 2)
if (k % i == 0)
return false;
return true;
}
I'll leave it to you to work out what to do with 2.

When i recurse the following code on function prime the program crashes what is wrong in my code?

Whenever I try to recurse in the function prime, my program crashes at that step. I think the problem is passing the function small as a recursion. What am I doing wrong?
#include <iostream>
using namespace std;
int smallest(int n) {
for( int x = 2 ; x <= n/2 ; x++){
if (n%x==0) {
return x;
}
else {
return 0;
}
}
}
int prime(int n, int(*small)(int)) {
int factor;
if (n == 1){
return 0;
}
else {
factor = n % small(n);
cout << small(n) << endl;
return prime(factor , small);
}
}
int main() {
prime(50 , &smallest);
return 0;
}
As the comments point out, when small returns 0, you continue recursing when you shouldn't. This can be solved with a small update to your base case:
if (n <= 1){
return 0 ;
}
Furthermore, it's worth pointing out that as it stands, your prime function will never call itself more than once. When you call smallest, you are guaranteed to get a prime number!

Value assignment into array c++

I'm trying to create a array of prime numbers done by calculation. As a project to learn coding. Ultimately to build my own math library so this is something I can add onto at a variety of levels as I learn to code c++.
The following is code that works great for printing prime numbers to the screen based on the search range, but my totalPrimes iterator is stuck at 1. So each time it places the last prime found in the PrimeNumbers[1] position.
Any advice would be awesome.
#include <iostream>
#include <array>
std::array<long, 10000000> PrimeNumbers={0};
void isPrime(long x);
int main() {
for (long i = 1; i < 10; i++) {
isPrime(i);
}
for(int h = 0; h < 10; h++) {
std::cout << "\nSecond Prime is : " << PrimeNumbers[h];
}
}
void isPrime(long x) {
int count(0), totalPrimes(0);
for (long a = 1; a < x; a++) {
if ((x % a) == 0) {
count += 1;
}
}
if (count == 1) {
++totalPrimes;
std::cout << '\n' << x << " is a Prime number";
PrimeNumbers[totalPrimes] = x;
}
}
You're initializing totalPrimes to 0 every time the function runs. You would need to have totalPrimes as a global variable, or better yet (because global variables can become problematic), set it equal to the first available member of PrimeNumbers before you do anything else in that function.
Keep track of a position along with your PrimeNumbers array.
size_t nLastPos=0;
...
for(size_t x = 0; 1000 > x; ++x)
{
if(isPrime(x))
{
PrimeNumbers[nLastPos++] = x;
}
}
for(size_t i = 0; nLastPos > n; ++n)
{/* print out number PrimeNumbers[n] */ }
It looks like you're having some trouble with variable scoping. The reason for your problem (as I noted in the comment) is that totalPrimes is local, so you're creating a new integer variable and setting it to 0 every time the function is called.
However, you've made PrimeNumbers global and are having the isPrime function modify it, which doesn't look like good practice.
All of this can be fixed with a little restructuring to make the code nicer:
#include <iostream>
#include <array>
bool isPrime(long x);
int main() {
std::array<long, 10000000> PrimeNumbers={0};
int totalPrimes = 0;
for (long i = 1; i < 10; i++) {
if (isPrime(i)) {
std::cout << '\n' << i << " is a Prime number";
PrimeNumbers[totalPrimes++] = i;
}
}
for(int h = 0; h < 10; h++) {
std::cout << h << " Prime is : " << PrimeNumbers[h] << std::endl;
}
}
bool isPrime(long x) {
int count(0);
for (long a = 1; a < x; a++) {
if ((x % a) == 0) {
count += 1;
}
}
return count == 1;
}
Your program can be re-structured little bit to make it easier to follow and debug.
Don't put things in isPrime other than the logic to decide whether a number is prime. Make sure it returns a bool. This will make the function a bit simpler and easier to debug.
Use the return value of isPrime in the calling function to perform other bookkeeping tasks.
The logic you have used to check whether a number is prime is incorrect. That needs to be fixed.
Here's an updated version of your posted code.
#include <iostream>
#include <array>
#include <cmath>
std::array<long, 10000000> PrimeNumbers={0};
bool isPrime(long x);
int main()
{
int totalPrimes = 0;
for (long i = 1; i < 10; i++)
{
if ( isPrime(i) )
{
std::cout << i << " is a Prime number" << std::endl;
PrimeNumbers[totalPrimes] = i;
++totalPrimes;
}
}
}
bool isPrime(long x) {
// 1, 2, and 3 are primes.
if ( x <= 3 )
{
return true;
}
// Even numbers are not primes.
if ( x % 2 == 0 )
{
return false;
}
// Check the rest.
long end = (long)std::sqrt(x);
for (long a = 3; a < end; a += 2) {
if ((x % a) == 0)
{
return false;
}
}
return true;
}
and its output:
1 is a Prime number
2 is a Prime number
3 is a Prime number
5 is a Prime number
7 is a Prime number
9 is a Prime number
Everybody is talking about how your totalPrimes variable is reset each time the function is called, and this is obviously true. You could return the value from the function and increment it from main, you could use global variables having the variable being defined outside of the function so that it's not reset each time inside the function or you could use
A static variable!
Take a look at this simple case. I have a function called up_two which increases the value of by two each time the function is called. The static variable int value has a memory of each time the function up_two() is called which increments value by two each time. If I were to use a just an integer it would always reset the value and have it be zero, which is what I initially defined it to be.
The advantage of using a static variable is that I can count how many times a function has been called, and I can keep my counter specific to a particular function.
#include <iostream>
using namespace std;
void up_two();
int main()
{
for(int i = 0; i < 10; i++)
{
up_two();
}
return 0;
}
void up_two()
{
static int value = 0;
cout << value << endl;
value += 2;
}
This program doesn't solve the particular problem that you want to solve, but if you figure out how the static variable is working, it should make your workflow easier.
The magic line here is this:
static int value = 0;
With it like this my program prints the following:
0
2
4
6
8
10
12
14
16
18
Without the static declaration, you just get 10 lines of zeroes
which is troublesome.
Hope that helps you optimize your program the way you want it to be.

How to print all prime numbers in c++?

I'm trying to print all the prime numbers in series, the code I ended up with is below, instead of printing all primes it prints random numbers, Some are prime and some are not :/
Why is that so?
#include <iostream>
using namespace std;
long int x,y=3;
int a=3;
bool isprime;
int main()
{
while(a<=100)
{
for(x=2;x<=y;x++)
{
if(y%x==0 && x!=y)
{
isprime=false;
break;
}
else if(y%x!=0 && x!=y)
{
isprime = true;
}
}
if(isprime==true && y%x!=0 && x!=y)
{
cout<<a<<" is a prime number."<<"\n";
isprime=false;
}
a++;
y++;
}
}
This
if(isprime=true && a%x!=0 && a!=y)
should be this
if(isprime==true && a%x!=0 && a!=y)
That's a common mistake. But even better is to realise that you don't need to compare bools against true of false, because they are true or false. So just
if (isprime && a%x!=0 && a!=y)
The logic just looks all wrong (and way too complicated), try this
isprime = true;
for(x=2;x<a;x++)
{
if(a%x==0)
{
isprime = false;
break;
}
}
if (isprime)
{
cout<<a<<"\n";
}
No need for y.
Well what jumps into my eyes is that you never increment y.
y is 3 in the beginning, so you only try if 2 is a possible divisor of a and then go to the next a.
Anyway, I am not sure what you wanted to achieve with y.
Let x run from 2 to a/2, as there is no need to try numbers bigger than a/2.
This is simply because there never will be a divisor bigger than a/2.
Example: a = 30. It would not make sense to try to divide by 16 or bigger, as the result can never be a integer (besides a itself of course)
However, this should do what you want:
int x = 0;
int a = 0;
bool isPrime = false;
for(a=3; a < 100; a+=2)
{
isPrime = true;
for(x = 2; x <= a/2; x++) {
if(a%x == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
cout << a << "\n";
}
}
there are of course other algorithms that can find primes, but I wanted to use your approach basically.
Cheers
Chris
EDIT:
Someone was faster :)
anyway: there is no need to run higher than a/2, this is a important optimization...!
EDIT2:
another optimization is of course skipping all even numbers, so start with a = 3 and increment by 2 for each loop iteration...
I see your code is ok now.
Nevertheless I made small changes, cleaning the code and making it a little bit faster.
#include <iostream>
using namespace std;
long int x, y = 2;
int a = 3;
bool isprime;
int main() {
while (a <= 100) {
while ((y + 1) * (y + 1) <= a) {
y++;
}
isprime = true;
for (x = 3; x <= y; x += 2) {
if (a % x == 0) {
isprime = false;
break;
}
}
if (isprime) {
cout << a << " is a prime number." << "\n";
}
a+=2;
}
}

Recursive/iterative functions

I'm having a bit of a hard time creating a function, using iteration and recursion to find the sum of all even integers between 1 and the number the user inputs. The program guidelines require a function to solve this three ways:
a formula
iteration
recursion
This is what I have so far:
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void formulaEvenSum(int num, int& evenSum)
{
evenSum = num / 2 * (num / 2 + 1);
return;
}
void loopEvenSum(int num, int& evenSum2)
{
}
int main()
{
int num, evenSum, evenSum2;
cout << "Program to compute sum of even integers from 1 to num.";
cout << endl << endl;
cout << "Enter a positive integer (or 0 to exit): ";
cin >> num;
formulaEvenSum(num, evenSum);
loopEvenSum(num, evenSum2);
cout << "Formula result = " << evenSum << endl;
cout << "Iterative result = " << evenSum2 << endl;
system("PAUSE");
return 0;
}
Using iteration to find the sum of even number is as given below.
void loopEvenSum(int num, int &evenSum2)
{
evenSum2=0;
for (i=2;i<=num;i++)
{
if(i%2==0)
evenSum2+=i;
}
}
The following code though not the most efficient can give you an idea how to write a recursive function.
void recursiveEvenSum(int num,int &evenSum3,int counter)
{
if(counter==1)
evenSum3=0;
if(counter>num)
return;
if(counter%2==0)
evenSum3+=counter;
recursiveEvenSum(num,evenSum3,counter+1);
}
Now you can call recursiveEvenSum(...) as
int evenSum3;
recursiveEvenSum(num,evenSum3,1);
You should be able to build an iterative solution using a for loop without too much problem.
A recursive solution might take the form:
f(a)
if(a>0)
return a+f(a-1)
else
return 0
f(user_input)
You have to differentiate between a case where you "dive deeper" and one wherein you provide an answer which doesn't affect the total, but begins the climb out of the recursion (though there are other ways to end it).
An alternative solution is a form:
f(a,sum,total)
if(a<=total)
return f(a+1,sum+a,total)
else
return sum
f(0,0,user_input)
The advantage of this second method is that some languages are able to recognise and optimize for what's known as "tail recursion". You'll see in the first recursive form that it's necessary to store an intermediate result for each level of recursion, but this is not necessary in the second form as all the information needed to return the final answer is passed along each time.
Hope this helps!
I think this does it Don't forget to initialize the value of evenSum1, evenSum2 and evenSum3 to 0 before calling the functions
void loopEvenSum(int num, int& evenSum2)
{
for(int i = num; i > 1; i--)
if(i%2 == 0)
evenSum2+=i;
}
void RecursiveEvenSum(int num, int & evenSum3)
{
if(num == 2)
{
evenSum3 + num;
return;
}
else
{
if(num%2 == 0)
evenSum3+=num;
num--;
RecursiveEvenSum(num, evenSum3);
}
}
void loopEvenSum(int num, int& evenSum2)
{
eventSum2 = 0;
for(int i = 1 ; i <= num; i++){
(i%2 == 0) eventSum += i;
}
}
void recurEvenSum(int num, int& evenSum3)
{
if(num == 1) return;
else if(num % 2 == 0) {
eventSum3 += num;
recurEvenSum(num-1, eventSum3);
}
else recurEvenSum(num-1, eventSum3);
}
btw, you have to initialize evenSum to 0 before calling methods.
the recursive method can be much simpler if you return int instead of void
void iterEvenSum(int num, int& evenSum2)
{
evenSum2 = 0;
if (num < 2) return;
for (int i = 0; i <= num; i+=2)
evenSum2 += i;
}
int recurEvenSum(int num)
{
if (num < 0) return 0;
if (num < 4) return 2;
return num - num%2 + recurEvenSum(num-2);
}
To get the sum of all numbers divisible by two in the set [1,num] by using an iterative approach, you can loop through all numbers in that range, starting from num until you reach 2, and add the number of the current iteration to the total sum, if this is divisible by two.
Please note that you have to assign zero to evenSum2 before starting the loop, otherwise the result will not be the same of formulaEvenSum().
void loopEvenSum(int num, int& evenSum2)
{
assert(num > 0);
evenSum2 = 0;
for (int i=num; i>=2; --i) {
if (0 == (i % 2)) {
evenSum2 += i;
}
}
}
To get the same result by using a recursive approach, instead of passing by reference the variable that will hold the sum, i suggest you to return the sum at each call; otherwise you'll need to hold a counter of the current recursion or, even worse, you'll need to set the sum to zero in the caller before starting the recursion.
int recursiveEventSum(int num)
{
assert(num > 0);
if (num == 1) {
return 0;
} else {
return ((num % 2) ? 0 : num) + recursiveEventSum(num-1);
}
}
Please note that, since you get an even number only if you subtract two (not one) from an even number, you could do optimisation by iterating only on those numbers, plus eventually, the first iteration if num was odd.