Hello everyone. this is my first post here. I am working on a prime number program that will output all primes from 1 to 100,000. I have the program working and running. It is to calculate the prime numbers and print seven per line. As of now it is printing a 0 for all non prime number instead of omitting them.
I am using code blocks software.
There are a lot of ways to find the prime numbers
Sieve of Eratosthenes is one of them, you could try it if you liked to
Besides, your code still have some space to improve, try to find out by yourself
And please no questions asked on why I did it this way. It's fast and that's all that matters. The only problem is that you might get one prime number over the value you want but... that's the only problem with it.
What's the point of posting? are you asking us to review it? refine it? etc?
I'm going to look up an algorithm for finding prime numbers and make a program....
I think there's a recurring function that will find prime numbers. I don't exactly remember it, but I think it's much more efficient. I will post back before the day's over.
prime numbers,
I remember writing one in BASIC on my old Dragon 32 computer back in the 80s.
(that's 32Kb RAM, sonny)
it slowed down after about 100 or so.
1MHz processor
8 bit
you kids don't know your born
<sucks on pipe>
then the psion organizer of course
<sucks on pipe>
i haven't tested this code for errors etc etc... as my eyeballs are on the brink of shutting down...
you'll still be able to get the gist of it though.
#include <iostream>
#include <cmath>
usingnamespace std;
#define MAX 100000
int main()
{
int array[MAX];
for(int a = 0; a <= MAX; a++)
array[a] += a+1;
for( int j = 1, j<= MAX; j++)
{
int i = 2;
while ( i <= sqrt(static_cast<double>(array[j]));
{
if (array[j] % i != 0)
array[j] = 0;
i++;
}
}
for(int a = 1; a <= MAX; a++)
{
cout << array[a] << " ";
if (!(a%7))
cout << endl;
}
return 0;
}
the method is from C++ Without Fear -- it's modified though... as if (array[j] % i != 0) would be if (array[j] % i == 0) and that would tell if it's not prime while mine tells that it is in fact prime... which i'm not sure is actually correct..
And why I did the +=6 thing? It's because of this
2 is prime
3 is prime
4 is not because %2
5 is prime
6 is not because %2 and %3
7 is prime
now I skipped to 12 and checked 12-1 and 12+1
8 and 10 are not because % 2
and 9 is not because % 3
skip to 18
14 and 16 are not because %2
15 is not because % 3
And all the numbers are like this. So it's useless to check them all. You increment with 6 and you check the one before and the one after. Then you increment again with 6 and repeat.
Sorry for my bad way of explaining things. I'm not good at explaining things. I just hope you got it.
The thing with math.h is for sqrt. You only need to check a number untill you reach sqrt of that number so if you know a better way to compute sqrt of a number, get rid of <math.h> and use that.