Prime Numbers different logic?

Here is the code I have written in C++ for displaying prime numbers from 3 onwards. I came up with the logic all by myself & did the coding myself.
There is no proper output.
I tried some debugging, but it didn't help. I don't wanna change my logic unless there is some kind of error. Please help me out. Thank you.

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
#include<iostream.h>
#include<conio.h>

int arr[100]; //Array to store the divisibility
int check=0;

void main()
{
clrscr();
float a, c;
int b;

cout<<"Prime numbers from 3 to 100 are:"<<endl;

for(int i=3; i<=100; i++)
{
//i will be the number we will check to see if it is prime
check=0; //So that when it runs the second time onwards, check is zero

for(int j=2; j<i; j++)
{

a=i/j; //a is float
b=a; //Decimal numbers will be dropped in "b"
c=b; //"c" will now store b, but as a float

if(a==c)
{
arr[j-2]=0; //0 to signify that the number was divisible
}

else
{
arr[j-2]=1; //1 to signify that the number wasn't divisible
}

}

for(int k=0; k<=i; k++)
{
//to check if "arr" contains any 0, i.e. if the number
//was divisible by any other number
if (arr[k]==0)
break;

else
check=1;

}

if(check==1)
cout<<endl<<i;
//prints the number if it is prime
}

getch();
}
Last edited on
The easy way to check a number if it's a prime is.

run through a loop from 2 until and including the square root of the number you're checking.
{if (number % i == 0) return false as it isn't a prime}
return true as it didn't get a 0 remainder in any of the former calculations.

The %-operator returns the remainder and its 0 if a division is successfull. i.e. the number aint a prime.

Translating this to C++ code is too easy to just post it here.

edit: wait...void main()?! The main function gets called expecting an int answer, so it should be int main().

Edit2: A float 1.0 can be 1.000002 and thus not = 1 I think I have read. Modulo operator is your friend here.
Last edited on
Topic archived. No new replies allowed.