for programming nerds ONLY!
Vitriola — Thu, 07/30/2009 - 08:24
Where I work, we often bet on programming puzzles. The latest bet was who could write a program to find all the prime numbers to a million that ran the fastest. While I primarily program in Delphi and Java, I really like ruby. Ruby is interpreted and I do not have the really fast version but I won by a large margin. Mine ran in under half a second. So, in the throes of my happy dance, I post the final code here.
If you are not a for real programmer, look away and save yourself NOW!
require 'benchmark'
highestPrime = 1_000_000
highestMultiple = Math.sqrt(highestPrime).to_i
primes = Array.new(highestPrime, true)
Benchmark.bm do |x|
x.report('primes') do
currentNum = 3
while currentNum < highestMultiple do
(currentNum*currentNum).step(highestPrime, currentNum * 2) { |i| primes[i] = false }
begin currentNum += 2 end until primes[currentNum]
end
end
end
# the print out
numWidth = highestPrime.to_s.length + 1
print 2.to_s.rjust(numWidth)
col = 2
3.step(highestPrime, 2) do |i|
if primes[i]
print i.to_s.rjust(numWidth)
col += 1
end
if col == 20
col = 1
puts ""
end
end


If you guys are really
Tankard — Fri, 07/31/2009 - 12:27If you guys are really interested in this kind of thing, look up how RSA security is done. It's based on the fact that you can determine if a number is prime very quickly, but you can't factor a number into primes very quickly. So, your keys are really large randomly determined prime numbers (like 128 bits or larger) that are used together to encode your message. The NSA has a standing money reward for anyone that can come up with a fast method for factoring numbers because that will break most of the encryption used today. The NSA also has HUGE supercomputers they use to just crunch through and decipher secure messages if they don't use a large enough number of bits in the keys. I recommend 1024 for anyone who cares, it would take years to decode.
I have looked at this many
Knoppix (not verified) — Fri, 07/31/2009 - 15:49I have looked at this many times and I don't even bother. The only thing I have cracked is WEP and PSK, PSK2 is much more secure.
Here is a quick and dirty example in LINQ
Knoppix (not verified) — Fri, 07/31/2009 - 10:29using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LinqTest { class Program { static void Main(string[] args) { List allNumbers = new List();
int numbersToSearchTo = 1000000;
var allNumbersVar = System.Query.Sequence.Range(2, numbersToSearchTo - 1);
allNumbers = allNumbersVar.ToList();
for (int div = 2; div < Math.Sqrt(numbersToSearchTo); div++)
{
var numbers = from num in allNumbers
where num % div != 0 || div >= num
select num;
allNumbers = numbers.ToList();
}
}
}
}
I don't like LINQ because to me it is bloated technology, it is also not nearly as fast (still runs in 1 thousandth of a second but alot slower) as my previous solution, but I thouhgt I would share.
c++
h4mm32 — Sat, 08/01/2009 - 11:24ive only ever taken C++ and this makes way more sense to me than what vit wrote
Much more terse than C# and I
Vitriola — Fri, 07/31/2009 - 11:31Much more terse than C# and I like that a good deal! thanks for posting it! Compiled will always run faster than interpreted all things being equal (or ceteris paribus for those that had years of latin and nowhere to use it). But I still love ruby and it is gaining in popularity for reasons other than execution speed.
The code above is C# LINQ is
Knoppix (not verified) — Fri, 07/31/2009 - 15:44The code above is C# LINQ is part of the .NET framework. I understand intrepreted will always be slower, compiled is 1:0 while interpreted is 100:0. I don't choose languages for their execution time I choose them for their sheer framework and capabilities.
(No subject)
Aidin — Fri, 07/31/2009 - 09:27girl nerd?
Vitriola — Fri, 07/31/2009 - 14:26She seems an odd duck as a nerd. She has the world analytical encyclopedia, which is not as good for reading as the britannica. She also has "alice's adventures in wonderland" which is clearly modernized as it descended from "Alice's adventures underground". There was also "through the looking glass" but we jumble things all up these days.
Now if the books were on high tech, math, or physics subjects, that would be something else. Granted that she is a cutie in an agreeable pose, but I thought that girls discontinued wearing panties when they developed red spots.
hmmm
h4mm32 — Sat, 08/01/2009 - 11:23im pretty sure thats a geometry book shes got there
I didnt even notice she had
Grasen — Sat, 08/01/2009 - 10:28I didnt even notice she had books till i read this post......
lol....that was u wasn't it
Aidin — Fri, 07/31/2009 - 13:30lol....that was u wasn't it saedo???
No no, the owner of the
saedo — Fri, 07/31/2009 - 13:39No no, the owner of the comment clearly says Aidin!
...
carno — Fri, 07/31/2009 - 12:36...
What do you do Vit? We might
carno — Thu, 07/30/2009 - 23:50What do you do Vit?
We might be hiring...
All of our stuff is in Ruby. It kicks so much ass. Do any of you do test driven development? (does such a thing even exist in windows)
Writing insurance software w/o testing would be like playing wow without addons.
I am heavy on test driven
Knoppix (not verified) — Fri, 07/31/2009 - 09:39I am heavy on test driven development using Nunit within my C# apps. I also use the Visual Studio default test for small apps sometimes but Nunit is really powerful. I also use an app to test web applications and their flow called Selenium. Programming languages that support OOP are the way to go and make testing a whole lot easier.
http://seleniumhq.org/
http://www.nunit.org/index.php
Awesome. I learned something
carno — Fri, 07/31/2009 - 12:55Awesome. I learned something new. <insert religious war about msft suckage, except their language designer>
If I get this instance mod working I'm volunteering everyone in this thread to test it! (that includes you aidin)
Selenium you mean?
Knoppix (not verified) — Fri, 07/31/2009 - 16:48Selenium you mean?
Btw you should all look into the power of the .NET 4.0 CLR and C#, you can hate M$ all you want but they are defiantly making the right moves.
I am not bashing other languages because that is a war that can never be won as everyone thinks their chosen language is better and of course M$ is always the devil and sucks, but the power that the framework it provides and the LOB (line of business) advantage it provides beats any other on the market. I am not being an evangelist, I have used JAVA, Python, Ruby, Ruby on Rails and PHP but to be honest the pure power and framework behind C# is unbeatable. The closest thing I would go to instead of C# is PHP and use CakePHP as it is very mature and is still gaining more popularity that any language other than C#. A lot of the hate and the use of open source programming languages comes from the idea that it costs to much to host, well you can get hosting for under $30 a month.
Here is a link for popularity:
http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
If you think it is expensive to program in .NET C# you are sorely mistaken, M$ provides a free IDE Visual Studio Express as well as a free database SQL Server Express and also if you want MySQL they have a full on API built for access into their database via .NET.
http://www.microsoft.com/express/download/
http://dev.mysql.com/downloads/connector/net/6.1.html
Java is slowly losing its popularity due to their inability to add any features to it unlike the hated M$ who strives to provide developers with cutting edge technology year after year, I will not be surprised if by 2012 C# is on top on this national statistical chart. The only reason C and C++ is still that high is because transition is still taking effect to phase it all out. C and C++ will always still have their place in this world to do low level operations such as operating systems and embedded circuits and such (because they are the closest thing to assembly and managing everything yourself, not going back to older languages than this) but I am sure eventually these will use more framework based languages. I still use C occasionally but they truly have no place for LOB applications, maybe if you want a rather non complex application built in 6 months or so C is ok, but for most businesses they want software done quickly more focus on business logic not managing memory etc.
Lastly by no means is it harder to maintain C# than any other language if your programmers have followed standards and programming paradigms it is no harder to maintain than any other language unless you let the script kiddies loose on your code and hired copy and paste programmers who don’t understand wtf they are doing then you have a problem no matter what language you use.
Well, languages have
Vitriola — Sat, 08/01/2009 - 05:27Well, languages have different perks to them. No matter how great the chef and how perfect the food, different people will order different dishes. That is just the way of things and I like it that way.
C# has a good deal going for it. Having Anders Hejlsberg in the lead makes a huge difference. I worked with him when I was an engineer at Borland. C# has, therefore, a LOT in common with Delphi, which makes it a good thing. I even know that he initially turned Bill G. down on the job offer and I know how Bill got him to change his mind.
The thing I like most about ruby is that it develops fast. Languages that are variations on "C" are verbose, and C# is no exception. Just take a peek at the difference in code size in this thread alone. If you go to codegolf.com, no "C" like language is even allowed to compete for obvious reasons.
I know that big websites can and do run on ruby. Twitter and Hulu included. I also know that maintenance takes so much time that yellowpages.com tossed their java website and rewrote it in ruby from scratch. That is a HUGE investment to make for ease of maintenance.
Still, C# has a lot of people that are using it. That would be a mix of people that would embrace anything MS pushes out and those that just develop in what is most commonly used, and those that actually prefer it.
<Rants against MS deleted here a few times>
I like that ruby is free and open source. That makes it much harder for someone to slip in something malignant. Also, it is a wonderful language that is specifically designed to make programmers happy, and it does. It lacks the bells and whistles that C# has. That is something that I miss. Still, if MS is making a ruby for .NET (http://www.ruby-forum.com/forum/34) then it definitely has its place in the sun.
FWIW & IMHO
All I have to say is holy
Finndo — Thu, 07/30/2009 - 13:57All I have to say is holy crap my math is rusty! I have been far too ingrained into Windows programming related to business logic nad not enough math problems!
...
Dikymo — Thu, 07/30/2009 - 15:40Im not sure how I feel about this thread yet.
It doesn't return 8. I think
Prime8 — Thu, 07/30/2009 - 13:26It doesn't return 8. I think its broken.
Well played.
Scaron — Fri, 07/31/2009 - 07:02Well played.
C# Primes corrected
Knoppix (not verified) — Thu, 07/30/2009 - 11:11using System; using System.Collections.Generic; using System.Diagnostics; namespace Primes { internal class Program { //-- This executes on my machine in: 00:00:00.0021929 private static int maxPrime = 1000000; private static bool[] numbers; private static List primes;
private static int squareRootOfMaxPrime;
private static void Main()
{
Stopwatch sw = new Stopwatch();
sw.Start();
List primeNumbers = GetPrimes();
sw.Stop();
TimeSpan ts = sw.Elapsed;
Console.WriteLine("Time: {0}", ts);
Console.ReadLine();
}
private static List GetPrimes()
{
squareRootOfMaxPrime = (int)Math.Sqrt(maxPrime);
numbers = new bool[maxPrime >> 1];
int maxPossiblePrimesLessThanN = (int)(1.1 * (maxPrime / Math.Log(maxPrime)));
primes = new List (maxPossiblePrimesLessThanN);
PopulatePrimes();
return primes;
}
private static void PopulatePrimes()
{
primes.Add(2);
for (int i = 3; i < maxPrime; i += 2)
{
int bitOffset = (i - 1) >> 1;
if (!numbers[bitOffset])
{
ScratchOffMultiplesOfThePrime(i, i << 1);
primes.Add(i);
}
}
}
private static void ScratchOffMultiplesOfThePrime(int prime, int addend)
{
if (prime > squareRootOfMaxPrime)
{
return;
}
for (int i = prime * prime; i < maxPrime; i += addend)
{
int bitOffset = (i - 1) >> 1;
numbers[bitOffset] = true;
}
}
}
}
Slighty optimized
Knoppix (not verified) — Thu, 07/30/2009 - 11:52using System; using System.Collections.Generic; using System.Diagnostics; namespace Primes { internal class Program { //-- This executes on my machine in: 00:00:00.0021347 private static int maxPrime = 1000000; private static bool[] numbers; private static List primes;
private static int squareRootOfMaxPrime;
private static void Main()
{
Stopwatch sw = new Stopwatch();
sw.Start();
List primeNumbers = GetPrimes();
sw.Stop();
Console.WriteLine("Time: {0}", sw.Elapsed);
Console.ReadLine();
}
private static List GetPrimes()
{
squareRootOfMaxPrime = (int)Math.Sqrt(maxPrime);
numbers = new bool[maxPrime >> 1];
primes = new List((int)(1.1 * (maxPrime / Math.Log(maxPrime))));
PopulatePrimes();
return primes;
}
private static void PopulatePrimes()
{
primes.Add(2);
for (int i = 3; i < maxPrime; i += 2)
{
if (!numbers[((i - 1) >> 1)])
{
RemoveMultiplePrimes(i, (i << 1));
primes.Add(i);
}
}
}
private static void RemoveMultiplePrimes(int prime, int addend)
{
if (prime > squareRootOfMaxPrime) { return; }
for (int i = prime * prime; i < maxPrime; i += addend)
{
numbers[((i - 1) >> 1)] = true;
}
}
}
}
This is will also return a
Knoppix (not verified) — Thu, 07/30/2009 - 14:00This will also return a list of integers so you can loop through them and see what they are, all of this is computed in much less than a half second (2.1347 millionths of a second), it is also accurate between 0 - 5,000,000 as the max prime number range to check.
I could probably make this shorter but I did a quick and dirty. I also tend to stick with compiled languages as they are alot faster.
So many nerds!
Vitriola — Thu, 07/30/2009 - 11:17I had no idea that we had so many programmers. I love it!!!
As to those that have not seen ruby before, think of it as "smalltalk: the next generation." It is terse enough that the whole prime number finding code is just this part:
currentNum = 3
while currentNum < highestMultiple do
(currentNum*currentNum).step(highestPrime, currentNum * 2) { |i| primes[i] = false }
begin currentNum += 2 end until primes[currentNum]
end
fyi, the step is one of the ways that ruby loops.
10.times {doSomething}
matches
for (int i = 1; i < 10; i++) { doSomething; }
3.step(100, 2) is analagous to
for (int i = 3; i < 100; i += 2)
It is a wonderful and elegant language. If anyone is interested, let me know and I will email some ebooks on the subject.
Yep I am using the Sieve Of
Knoppix (not verified) — Thu, 07/30/2009 - 10:34Yep I am using the Sieve Of Eratosthenes implementation, I am rewritting a full example with extra functionality as we speak because work can be boring :P
Ah yea, I think I see it in
saedo — Thu, 07/30/2009 - 10:37Ah yea, I think I see it in yours now. Never dealt with that language before lol
The code block that did stay
Knoppix (not verified) — Thu, 07/30/2009 - 11:00The code block that did stay in there was wrong, but I am just about done.
Umm... C# maybe? Well
saedo — Thu, 07/30/2009 - 10:24Umm... C# maybe? Well it'll be similar to other C I suppose. To get speed is the game, memory is fully exploited.
const int HIGHEST_PRIME = 1000000;
const int HIGHEST_MULTIPLE = 1000; // sqrt of above, manually type it so it doesn't call a math function
bool primes[] = new new bool[HIGHEST_PRIME];
primes[0] = primes[1] = 0;
for (int i = 2; i < HIGHEST_PRIME; i++)
primes[HIGHEST_PRIME] = 1;
int currentPrime = 2;
while (currentPrime < HIGHEST_MULTIPLE)
{
// mark multiples as not prime
for (int i = currentPrime+currentPrime; i < HIGHEST_PRIME; i+= currentPrime)
primes[i] = 0;
// search for the next candidate
for (int i = currentPrime + 1; i < HIGHEST_MULTIPLE; i++)
if (primes[i])
{
currentPrime = i;
break;
}
}
// That should get the primes in the array, I think, true if prime, false if not. Sieve method. Doing this all on the fly in the head lol
// Printing it if you so choose
for (int i = 0; i < HIGHEST_PRIME; i++)
if (primes[i])
Console.WriteLine("{0}.", i);