What is wrong with this code?

Jan 14, 2012 at 11:47am
I wrote this code to find out the next prime number to a user given number.But it is not working as intended.I am a beginner,so any major/minor error/s are possible.Anyone care to find it out please?
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
#include <iostream>
#include <cmath>

using namespace std;

int prime_test(int i);

int main()
{
    int x;
    cout<<"input a number "<<endl;
    cin>>x;

    cout<<"the prime number next to "<<x<<" is "<<prime_test(x);
    return 0;
}

int prime_test(int i)
{
    int z;

    while(true)
    {
        for(int d=2;d<=sqrt(i);d++)
        {

            if (i%d==0)
            continue;
            else
            z=true;
        }
        if(z)
        return i;
        else
        i++;
    }
}
Jan 14, 2012 at 11:54am
You forgot to initialize z.
Jan 14, 2012 at 11:57am
what exactly do you mean by initializing z?
Jan 14, 2012 at 12:16pm
I mean that you should give z a value before using it.
Jan 14, 2012 at 12:18pm
mm,it still doesn't work.Any idea why?
Jan 14, 2012 at 12:28pm
@ offcutter: you do that by e.g. int z = false;
By the way, int is used for numbers.
So if you only store true or false, you should use bool, as in bool z = false; instead.

A thing to remember later on: try to split your problem into small pieces, that each do simple things.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bool is_prime(int i)
{
    for (int d=2; d <= sqrt(i); ++d) // ++d or d++ has same effect in this case
        if (i%d == 0)
            return false;

    return true;
}

int test(int i)
{
    while (!is_prime(i)) // while our i isn't a prime,
        ++i; // increase it

    return i;
}
Jan 14, 2012 at 12:31pm
The for loop is wrong. When you find that i%d==0 you know that the number i is not a prime number so you should stop the for loop and set z to false. As it is now you just skip to the next iteration of the for loop.
Only if i%d != 0 for all numbers in the loop you know that i is a prime number. To check this you can set z to true before the for loop. If it's still true afterwards you know that it's a prime number.
Topic archived. No new replies allowed.