Prime Number's order problem

Hello everyone, i have a problem regarding this code:

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
#include <iostream>

using namespace std;

int getprimen(unsigned short which)
{
    unsigned short fnumber = 1, cnumber = 0;

    while(which != cnumber)
    {
        fnumber++;
        cnumber++;
        unsigned short i;

        for(i = 2; i <= fnumber / 2; ++i)
        {
            if(fnumber % i != 0){cnumber++;}
        }
    }

    return fnumber;
}

int main()
{
    cout<<getprimen(3)<<endl;

    return 0;
}


Which generates prime numbers in their order, by unsigned short which i mean to return that number from the order, for example, the first prime number is 2, so getprimen(1) which gets me 2, getprimen(2) which gets me 3, but everything past 3 is wrong and i dont know where is the problem, so, anyone can help me figure this out? Thanks in advance!
your logic makes no sense, but perhaps you're having troubles with the language, so write a pseudocode and we'll work from there.
and use meaningful names for your variables, ¿what's the purpose of `fnumber' and `cnumber'?
Last edited on
+ne555
ok, i'll do it will pseudocode, and variables such as "fnumber" (final number) and "cnumber" (counting number) are my way of writing temporary code.
looks like cnumber is ++ no matter what. I don't see how this is supposed to find primes. Also fnumber/2 is probably supposed to be sqrt().

also it starts over for each input, it should save previous work done and resume from there or you will be here for eternity just doing small primes.

there are a bunch of ways to find small primes.
the brute force way is (for i = 2 ... sqrt(n) .. ) if(n%i == 0) not prime, move to next n.


Last edited on
> "fnumber" (final number) and "cnumber" (counting number)
number is not the important part, and you are not interested in simple numbers, but in those that are primes.
your naming is awful.

> Also fnumber/2 is probably supposed to be sqrt().
let's not worry about the efficency of wrong code, let's work on the logic first.
Anyways, i managed to fix my problem with another code, which is this one:
(made by me)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int getprimen(unsigned long int which)
{
    unsigned long long int fnumber = 1, cnumber = 0;

    while(which != cnumber)
    {
        fnumber++;
        unsigned long long int i;
        bool isPrime = true;

        for(i = 2; i <= fnumber / 2; ++i)
        {
            if(fnumber % i == 0)
            {
                isPrime = false;
                break;
            }
        }
        if(isPrime == true) {cnumber++;}
    }

    return fnumber;
}


I know its very poorly optimised but im gonna reply again with another faster version
Topic archived. No new replies allowed.