Hey. I'm a newbie. I've been programming in C++ for about 2 weeks. I was wondering if anyone knows how to write a program to find primes between 1 and 1 million. Preferably under 10 Seconds, but not a requirement.
I'm with Bazzy use that algorithm it's good however, I don't think you will be able to find the primes in that range because when i tried my program crashed.
Chances are, you just got an amazing overflow error.
@OP: I don't think you'll have an easy time finding that many primes in that timeframe, especially if you plan on outputting them. (And at your current experience level, I would doubt that you have the optimization techniques at your disposal to accelerate the runtime.) However, the sieve is probably the best algorithm in question. Beyond that, the runtime of your code is going to be largely out of your hands, as the compiler will do what it can to optimize your code and not much more.
Thanks guys. I knew about the Sieve of Eratosthenes, but I wasn't sure exactly how to implement that into C++ code. Grey Wolf, your code works for me, except for the fact that it doesn't show all of the primes. That's okay though, it gave me somewhere to start. Oh, and also, I just watched my teacher, run a program, which printed all the primes between 2 and a million in two seconds. Just thought that you might want to know.
Passing data between bridges has a relatively high overhead, not only because of the "bureaucracy" involved, but also due to the physical distance. To that, add the response time of specialized logic and mechanical parts in the devices. And then there's problematic virtual devices, as well. For example, printing to the console in Windows is hundreds of times slower than redirecting to the file system.
The one device that has been an exception to this rule is the screen. AGP and PCI-E video cards are connected to the Northbridge with very high bandwidths. Video RAM is almost a secondary main memory. (Furthermore, modern video cards are miniature [super]computers in themselves, but I digress.)
Here's a program I wrote this morning that uses the sieve algorithm. My IDE (Borland 5.02) is a little old, but the code works. I put in two loops, one that finds the primes and one that prints them to demonstrate the slow output. Enjoy.
It will generate and output the first 100 primes. If you want a different number of primes, then
change the 100 in the first for() loop to whatever value you like.