Help with primes program

Pages: 12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <cmath>

using namespace std;

// FUNCTION PROTOTYPE FOR read_range
void read_range(int& imin, int& imax);

// FUNCTION PROTOTYPE FOR is_prime
bool is_prime(int& k);

// DO NOT MODIFY THE MAIN ROUTINE IN ANY WAY
int main()
{
int imin(0), imax(0);


// Read in range
read_range(imin, imax);

// Print prime numbers

cout << "Primes:";
for (int k = imin; k <= imax; k++)
{
if (is_prime(k))
{
cout << " " << k;
}
}
cout << endl;

return 0;
}

// DEFINE FUNCTION read_range() HERE:
void read_range(int& imax, int& imin)
{
cout<<"Enter minimum and maximum:";
cin>>imin>>imax;
while(imin>imax)
{
cout<<"Error, Minimum must be less then maximum"<<endl;
cout<<"Enter minimum and maximum:";
cin>> imin>>imax;
}
while((imin<2 || imax<2))
{
cout<<"Error, Minimum and maximum must be at least 2"<<endl;
cout<<"Enter minimum and maximum:";
cin>> imin>>imax;
}
}


// DEFINE FUNCTION is_prime() HERE:
bool is_prime(int& k)
{
int count=0;
for(int i=2; i<=(k-1); i++)
{
if (k%i !=0)
count++;

}
if (count=(k-2))
true;


}



sorry here is the code with code tags actually working.
Thanks.

Here, function bool is_prime(int& k); is supposed to return a bool. But the function just terminates without returning anything.

Line 66 is wrong, it uses '=' instead of '==' so will always be true.

Some of my previous comments still apply, you don't actually need to count anything.

At lines 62-63, all that's required is to return false when (k%i) is zero, otherwise, if you reach the end of the for loop the number must be prime, so return true.

Last edited on
so i changed it so that its

if(k%i==0)
return false;
else
true;..

and it still wont print any primes. what am i doing wrong to make it the function actually return true or false.
1
2
3
4
if (k%i==0)
    return false;
else
    true;


Line 4 is wrong. It should say return true;
But that's not enough, the if/else above won't work.

You need the for-next loop where the number is tested for division by each value of i. Inside that loop, place this code:
1
2
 if (k%i==0)
    return false; 

After the end of the loop, (outside the loop) place the return true statement.

1
2
3
4
5
6
7
8
9
10
bool is_prime(int& k)
{
  for(int i=2; i<=(k-1); i++)
    {
      if (k%i ==0)
	return false;
      
    }
  return true;
}


is this what you mean? because if so this isnt working either. It still only prints
Primes:
. I sent you a private message a while ago, would it be possible to continue through emails or other ways of communication for easier response ext.
@ProgramingNewb I sent a reply to your message.
Topic archived. No new replies allowed.
Pages: 12