As the name asks, what's your favourite prime generator you've written? Mine would probably be very similar to another one, but without those segmentation faults:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
usingnamespace std;
int main()
{
int max;
std::cin>>max;
bool *sieve = newbool[max];
for(size_t i = 0; i < max+1; ++i)
{
sieve[i] = true;
}
sieve[0] = false;
sieve[1] = false;
for(size_t i = 0; i < max+1; ++i)
{
if(sieve[i] == true)
{
for(size_t w = i*2; w < max+1; w+=i)
{
sieve[w] = false;
}
}
}
std::string answer[2] = {" "," not "};
for(size_t i = 0; i < max+1; ++i)
{
std::cout<<i<<" is"<<answer[sieve[i]?0:1]<<"a prime."<<std::endl;
}
std::getchar();
std::getchar();
delete[] sieve;
return 0;
}
EDIT: Memory leak.
Also, Whovian, you should probably allocate memory for your vector at the beginning like Albatross, since re-sizing is pretty costly. You'll use more memory, but get better performance.
Are you kidding me Albatross? That's the most beautiful program I've ever seen. I like how you modularized checkprimeness, and the system calls are extremely useful for portability. And everyone knows malloc is much safer than new. Who would trust their memory allocation to the compiler to figure out? That's just silly.
I didn't know how to write a prime number generator, so I decided to write a prime number generator generator instead. Then I didn't know how to do that, so I wrote a prime number generator generator generator: http://codepad.org/oHth65wk
[edit] Notice how a 3 kiB file generates a 2 kiB file which generates a 480 byte file (which is the complete opposite of what metaprogramming is supposed to do).
And as long as we're at it, miller-rabin test for primality
todo: add random num gen at todo, allow k as parameter
Also, it uses a typedef 'UInt4' which is a typedef of the ttmath uint, with one modification, an inclusion of a powmod function which I've included. Note that you can't always just take the power then modulus for large exponents without requiring prohibitively large numbers. You can make it work with anything though, just templatize as appropriate, and make PowMod another templated function instead of a method of uint4.
I just had mine print every prime up to 2,147,483,647 (INT_MAX) and it finished in just under 41 minutes. Is that good or bad?
I was about to say you can probably improve it, by disregarding numbers divisible by primes under 100, thereby reducing used space and also the time to build it (which is where much of those 41 minutes was spent).