error with function

Im writing a program that uses a thread when you enter a number,displays its prime numbers.the program runs but it just displays all of the numbers in order and not just the primes.

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
#include <windows.h>
#include <iostream>
#include<cmath>
#define MAX_THREADS 1
using namespace std;
DWORD WINAPI primenum(LPVOID);
int main(int argc, char *argv[])
{
    DWORD ThreadId;
    HANDLE ThreadHandle;
    int num = 0;
    cout<<"Enter a number and it will generate the prime numbers:"<<endl;
    cin>>num;
   
   ThreadHandle = CreateThread(NULL,0,primenum,&num,0,&ThreadId);
   
   for(int i = 0; i < MAX_THREADS; i++) {
   CloseHandle(ThreadHandle);
   }
   system("pause");
   return 0;
  
}
DWORD WINAPI primenum(LPVOID n){
int* pNum = (int*)n;
for( int i = 1; i <= *pNum; i++ ) { 
      if(DWORD(*pNum) % 2 == 0){
           cout<<i<<" is a prime number"<< endl;
                 }
      }
      return DWORD(*pNum);
}


if someone can help me out i would appreciate it.
Well, by looking at the code, I think the problem is DWORD(*pNum) % 2 == 0)
I think DWORD(*pNum) is even number, and since you are always dividing it by the same number and also you are not breaking from the loop when the number is divisible. Therefore, it is printing out all the numbers. I guess the logic should be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int flag = 1; 
for (int i = 2;  i < *pNum; i++) { 
 
     if (DWORD(*pNum) % i == 0)  { 
        flag = 0; 
        break; 
     }
}

if (flag == 1) { 
    cout<<*pNum<<" is a prime number";
}
else { 
    cout<<*pNum<<" is not a prime number";
 } 


Hope this helps !
Last edited on
thanks it does.
Topic archived. No new replies allowed.