Downfall - "Droppin bombs since '04"

  • home
  • forums
  • calendar
  • gallery
  • handbook
  • raid hub
  • epgp
Home › Forums › World of Warcraft General › Everything Else

for programming nerds ONLY!

Vitriola's picture

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
 

‹ Endgame comparison - FFXI vs. WoWdallas area folks ›
  • Everything Else

If you guys are really

Tankard — Fri, 07/31/2009 - 12:27

If 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:49

I 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:29
using 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:24

ive only ever taken C++ and this makes way more sense to me than what vit wrote

Vitriola's picture

Much more terse than C# and I

Vitriola — Fri, 07/31/2009 - 11:31

Much 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:44

The 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.

Aidin's picture

(No subject)

Aidin — Fri, 07/31/2009 - 09:27

Vitriola's picture

girl nerd?

Vitriola — Fri, 07/31/2009 - 14:26

She 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:23

im pretty sure thats a geometry book shes got there

Grasen's picture

I didnt even notice she had

Grasen — Sat, 08/01/2009 - 10:28

I didnt even notice she had books till i read this post......

Aidin's picture

lol....that was u wasn't it

Aidin — Fri, 07/31/2009 - 13:30

lol....that was u wasn't it saedo???

saedo's picture

No no, the owner of the

saedo — Fri, 07/31/2009 - 13:39

No no, the owner of the comment clearly says Aidin!

carno's picture

...

carno — Fri, 07/31/2009 - 12:36

...

carno's picture

What do you do Vit? We might

carno — Thu, 07/30/2009 - 23:50

What 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:39

I 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

carno's picture

Awesome. I learned something

carno — Fri, 07/31/2009 - 12:55

Awesome. 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:48

Selenium 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.

Vitriola's picture

Well, languages have

Vitriola — Sat, 08/01/2009 - 05:27

Well, 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

Finndo's picture

All I have to say is holy

Finndo — Thu, 07/30/2009 - 13:57

All 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's picture

...

Dikymo — Thu, 07/30/2009 - 15:40

Im not sure how I feel about this thread yet.

Prime8's picture

It doesn't return 8. I think

Prime8 — Thu, 07/30/2009 - 13:26

It doesn't return 8. I think its broken.

Scaron's picture

Well played.

Scaron — Fri, 07/31/2009 - 07:02

Well played.

C# Primes corrected

Knoppix (not verified) — Thu, 07/30/2009 - 11:11
using 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:52
using 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:00

This 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.

Vitriola's picture

So many nerds!

Vitriola — Thu, 07/30/2009 - 11:17

I 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:34

Yep 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

saedo's picture

Ah yea, I think I see it in

saedo — Thu, 07/30/2009 - 10:37

Ah 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:00

The code block that did stay in there was wrong, but I am just about done.

saedo's picture

Umm...  C# maybe?   Well

saedo — Thu, 07/30/2009 - 10:24

Umm...  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);

  • 1
  • 2
  • next ›
  • last »

Random image

Knoppix in Bora Bora

Navigation

  • Content
  • Raid Parses
  • The Downfall Handbook
  • User list
  • Polls
  • Groups
  • Popular content

Who's new

  • Babyconan
  • Grantlius
  • Ecology
  • fumabomb
  • firstslacker

Latest image

PMS Logo for Legion

Archives

  • September 2016 (1)
  • August 2016 (5)
  • July 2016 (8)
  • June 2016 (2)
  • May 2016 (1)
  • March 2016 (3)
  • February 2016 (2)
  • January 2016 (5)
  • August 2015 (1)
  • May 2015 (3)

Recent comments

  • App closed with extreme
    7 hours 17 min ago
  • Guild App closed at his
    4 weeks 1 day ago
  • Once we get the new site,
    7 weeks 1 day ago
  • Is the time frame posted in server time?
    7 weeks 2 days ago
  • Awesome. Thanks. Once I
    9 weeks 1 day ago
  • I'd be happy to stick around
    9 weeks 1 day ago
  • Possibly
    9 weeks 1 day ago
  • More necro
    10 weeks 2 days ago
  • Story time!
    11 weeks 3 days ago
  • I;ve downladed drop box, if
    13 weeks 17 hours ago

Active forum topics

  • April 1st 2006
  • Nostalarious: "Blizzard wants Vanilla servers"
  • Galaga 13/13 Heroic by Deposing A Tyrant
  • Poker Face Achieves in one night! Glory of Hellfire Raider
  • Glory of The Hellfire Raider
  • Galaga Destroys Heroic Archimonde AOTC 12/13H
  • Galaga takes out Thomas the Train (7/10 H BRF)
more

Recent blog posts

  • So I guess this is the end...
  • Shaedo's Soloing Extravaganza
  • Shaedo UI Extravaganza
  • Big site updates this weekend!
  • This is for all the Hearthstone players out there
  • My First Full Day on Beta
  • State Of <Downfall> 2014
  • Scaron taking a break
  • How Gorgonnash's Connections went
  • Let's Talk about Mythic Raids
more

Poll

What do you think about no flying for an entire expansion?
YES) It makes me feel more immersed in the game lore.
15%
YES) It encourages more PvP! (Please explain how in comments)
5%
YES) I miss riding my ground mounts.
9%
MAYBE) If you make all of my flying mounts able to be ground too.
8%
MAYBE) if ground mounts are sped up to 200% speed (or higher)
26%
NO) I don't have enough time when I'm on to be riding everywhere
7%
NO) I have spent too much time getting various levels of flying to be wasting it.
11%
NO) It encourages more PVP! (please explain in the comments)
0%
NO) I love flying.
19%
Total votes: 74
  • 38comments
  • Older polls

Popular content

All time:

  • Professor Putricide Strategy Page
  • Rotface Strategy Guide
  • Arthas, the Lich King Strategy Page
  • Sindragosa Strategy Page
  • Toravon the Ice Watcher Strategy Guide
  • home
  • forums
  • calendar
  • gallery
  • handbook
  • raid hub
  • epgp

I notice your oeuvre is monochromatic.
This site is proudly powered by Drupal.