Click here to Skip to main content
6,933,325 members and growing! (15,137 online)
Email Password   helpLost your password?
 
General Programming » Algorithms & Recipes » General     Intermediate

High Speed Prime Numbers Calculation

By Mariano Abdala

This article shows a high speed Prime Numbers calculation.
C#, Windows, .NET1.0, .NET1.1VS.NET2003, Dev
Posted:19 Aug 2004
Updated:17 Feb 2005
Views:120,730
Bookmarked:19 times
printPrint Friendly   add Share
      Discuss Discuss   Broken Article?Report  
40 votes for this article.
Popularity: 3.06 Rating: 1.91 out of 5
24 votes, 60.0%
1
3 votes, 7.5%
2
3 votes, 7.5%
3
4 votes, 10.0%
4
6 votes, 15.0%
5

Introduction

I spend a lot of time, making programs capable of coming out with a large collection of prime numbers, for any use.

Let�s assume all of you know what a prime number is. The usual way for programs to calculate a number of prime numbers is collecting prime numbers one number at the time, calculating the next prime number, adding it to the previous list.

  • 2 Is prime number, because it�s divisible only by itself and 1.
  • List is now {2}.
  • 3 Is prime number, because it�s divisible only by itself and 1.
  • List is now {2, 3}.
  • 4 Is not a prime number, because it�s divisible by 2, the 0th item of the list.
  • 5 Is prime number, because it�s divisible only by itself and 1.
  • List is now {2, 3, 5}.
  • 6 Is not a prime number, because it�s divisible by 2, the 0th item of the list.
  • 7 Is prime number, because it�s divisible only by itself and 1.
  • List is now {2, 3, 5, 7}.
  • 8 Is not a prime number, because it�s divisible by 2, the 0th item of the list.
  • 9 Is not a prime number, because it�s divisible by 3, the 1st item of the list.
  • 10 Is not a prime number, because it�s divisible by 2, the 0th item of the list.
  • And so on...

I�m not dividing the number 10 with other numbers whether they are or not prime number, because, there�s no use doing it. There�s no use on dividing a number by 2 and by 4, because 4 is 2 times 2, 6 is 2 times 3, and so on.

An appropriate algorithm to do this would be:

ArrayList primeNumbers = new ArrayList();

for(int i = 2; i < 100; i++)
{
    bool divisible = false;

    foreach(int number in primeNumbers)
        if(i % number == 0)
            divisible = true;

    if(divisible == false)
        primeNumbers.Add(i);
}

It works, and I do it fast. For each number for 2 to 100, it's dividing lots of times. If you are trying to get 100,000 prime numbers, the thing gets messy. But I am happy making my programs faster, improving its mechanisms, gaining in memory, writing them on assembler!, and that sort of things. But just then I found the The Sieve of Eratosthenes that made me open my eyes. This method, works as follows:

  1. Write down the numbers 1, 2, 3, ..., n. We will eliminate composites by marking them. Initially all numbers are unmarked.
  2. Mark the number 1 as special (it is neither prime nor composite). Set k=1. Until k exceeds or equals the square root of n, do this:
    1. Find the first number in the list greater than k that has not been identified as composite. (The very first number so found is 2.) Call it m.
    2. Mark the numbers 2m, 3m, 4m, ... as composite. (Thus in the first run, we mark all even numbers greater than 2. In the second run, we mark all multiples of 3 greater than 3.) m is a prime number. Put it on your list.
    3. Set k=m and repeat.
  3. Put the remaining unmarked numbers in the sequence on your list of prime numbers.

You can try making this on your own. It�s really easier and faster. Because you�re not dividing, you are just jumping equal numbers of spaces.

So I figured, if this method makes it easier for me, what could it make for a machine!? I had all I needed, so I started programming it. I�ve had a sheet of paper (an ordered array of booleans), and the jumping action� the for() statement!!! The results were amazing. I�ve calculated the first 3,000,000,000 numbers and distinguished them into primes and composites in just 10 minutes! Something impossible with the previous algorithm. The only difficulty is that you will need a huge memory, to go over this number. Obviously, this method, consumes lots of memory, but it�s a great way of getting fast the first hundreds of millions of prime numbers. So, you can go on with some other algorithm, working on disk, or something like that.

So, no more preambles, here's the code:

using System.Collections;

int topNumber = 1000000;
BitArray numbers = new BitArray(topNumber, true);

for(int i = 2; i < topNumber; i++)
    if(numbers[i])
    {
        for(int j = i * 2; j < topNumber; j += i)
            numbers[j] = false;
    }

int primes = 0;

for(int i = 1; i < topNumber; i++)
    if(numbers[i])
    {
        primes++;
        //Console.Out.WriteLine(i);

    }

Console.Out.WriteLine();
Console.Out.WriteLine(primes + " out of " + topNumber + " prime numbers found.");
Console.In.ReadLine();

//Tnx Bistok for your help!

I would hardly recommend you that you do not uncomment the Console.Out.WriteLine line, it really slows it all down, and that�s not the point of all these.

If you have a good machine and you make it to calculate a really big number of primes, please let me know, and if any of you has any suggestions either.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Mariano Abdala


Member
My name is Mariano Abdala, I'm from Buenos Aires, Argentina. I've lived half a year in Rio do Janeiro, Brasil and a hole year in San Sebastián, Spain.

I've been developing software now for four years as a professional, but I'm doing these since I was a child. Actually, I run my first piece of software at the age of 9. It was a simple Logo code. You was asked to make decisions about a tale and the tale itself take form as the user plays it.

I'm really looking foward to discover and practice the 'state of the art' of software developing.
Occupation: Web Developer
Location: Argentina Argentina

Other popular Algorithms & Recipes articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 45 (Total in Forum: 45) (Refresh)FirstPrevNext
GeneralThe Best And Easy Of Prime Number Is Pinmembermehranrezaie1:44 28 Oct '08  
GeneralLOL Pinmemberbaks2565:09 31 May '07  
GeneralRe: LOL PinmemberMariano Abdala5:22 31 May '07  
Generalhigh speed prime numbers Pinmemberprasofty21:43 20 May '07  
GeneralRe: high speed prime numbers PinmemberMariano Abdala2:03 21 May '07  
GeneralHigh Speed ? Pinmemberamircorrtec19:19 18 Feb '07  
GeneralRe: High Speed ? PinmemberMariano Abdala1:17 19 Feb '07  
NewsI have a algorith plus quick that. PinmemberMauricioFox21:44 22 Jul '06  
GeneralHmmmm...... PinmemberPaul Conrad21:28 11 Jul '06  
GeneralYet one more suggestion. Pinmemberpetrowi12:21 20 Jun '06  
GeneralYet another suggestion Pinmembermontclaris18:29 24 Jan '06  
GeneralWheel Factorization Pinmemberdanielibarnes13:06 11 Nov '05  
GeneralFalse Primes Pinmemberjmoral411:30 24 Aug '05  
GeneralRe: False Primes PinmemberMariano Abdala11:38 24 Aug '05  
GeneralRe: False Primes Pinmemberjmoral423:40 24 Aug '05  
GeneralRe: False Primes PinmemberMariano Abdala4:45 25 Aug '05  
GeneralRe: False Primes PinmemberMember 29450828:09 13 Jan '09  
GeneralI've done something similar PinmemberYan Yorga3:47 15 Dec '04  
GeneralRe: I've done something similar PinmemberMariano Abdala5:23 16 Feb '05  
Hi! Tnx for the comment. About the probability method, my intention never was to discredit it. I think it's great, but it can't be aplied to 'my' method.

I've been investigating a little more about what my application was capable of, and discover that most of those 10 minutes I talk about, the machine was swapping memory onto the HD. And about 10 SECONDS were really used to run the program algorithm. I did this program in C# as a way to probe that The Sieve Of Erastotenes was the best way of calculating ALL prime numbers in a computer. I think I've probe it right. To extend this program, it would have to be written maybe in assembler and run as much as possible into RAM and the rest of it into a HD o any large storage unit.

In fact, most of the time of the whole process is getting a place to storage the result and a little bit of it to run the algorithm. That's way, I think, most of developmet to extend the program would be destinated to program an efficient way to get space and storage the results.

Way did you get interested into calculating prime numbers? Are you working on something related to it?

Greetings.

Mariano, el estupefacto. WTF
//TODO: Make this damn code work!
GeneralOne More Suggetion PinsussPrashant Mishra15:57 21 Oct '04  
GeneralHigh speed? I think not. PinmemberJörgen Sigvardsson9:29 20 Aug '04  
GeneralRe: High speed? I think not. Pinmember|\/| /\ |Z ! /\ |\| []9:35 20 Aug '04  
GeneralRe: High speed? I think not. PinmemberJörgen Sigvardsson9:53 20 Aug '04  
GeneralRe: High speed? I think not. Pinmember|\/| /\ |Z ! /\ |\| []12:04 20 Aug '04  
GeneralRe: High speed? I think not. PinmemberJörgen Sigvardsson12:07 20 Aug '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+PgUp/PgDown to switch pages.

PermaLink | Privacy | Terms of Use
Last Updated: 17 Feb 2005
Editor: Nishant Sivakumar
Copyright 2004 by Mariano Abdala
Everything else Copyright © CodeProject, 1999-2010
Web11 | Advertise on the Code Project