2009-03-08

Abstruse Goose and Prime Riddles

So i'm a real maths geek. And seeing the latest Abstruse Goose comic on Saturday morning lead me to solving a math problem with code. By the time i got to the last piece of the riddle ( it's a 3 parter ), i decided that looking and guessing would take too long, so i figured that it was an easy enough problem to solve in code. Less than an hour later, i had a quick C# program that solved the problem. It took considerably longer than it would for me in C++, mainly because there were many things i needed to look up. So here it is:

using System;

public class MainClass

{

 public static void Main (string[] args)

{

 if( args.Length != 2 )

 {

  Console.WriteLine("Usage: PrimeFinder <n> <digits>");

  Console.WriteLine("where n is the length of the prime you are looking for and digits is the search space" );

  return;

 }

 

 int count = Convert.ToInt32( args[0] );

 

 if( count > args[1].Length )

 {

  Console.WriteLine("Number of digits was longer then the search space");

  return;

 }

 

 

 for( int i =0; i<=args[1].Length-count; i++ )

 {

  string current = args[1].Substring( i, count );

  Int64 toCheck = Convert.ToInt64( current );

  if( isPrime( toCheck ) )

  {

   Console.Write("Found Prime: ");

   Console.WriteLine( toCheck );

   return;

  }

 }

 

 Console.WriteLine("No primes found");

}

 

 public static bool isPrime( Int64 numberToCheck )

{

 Int64 limit = (Int64)Math.Ceiling( Math.Sqrt( numberToCheck ) );

 

 

 for( Int64 i = 2; i <= limit; i++ )

 {

  Int64 rem;

  Math.DivRem( numberToCheck, i, out rem );

  

  if( rem == 0 )

  {

   return false;

  }

 }

 return true;

}

}

Basically, you specify a search space of numbers and the length of the prime you are looking for and it will return the first prime of that size in the search space.

Now that was fun! Furthermore, i did a quick port of that code to Android with a simple ui. In the end, i have to say that MonoDevelop was far nicer to work with than Eclipse has ever been, and i don't feel like my pc is struggling to allocate free memory for the IDE.

As for the Android app, it will eventually make its way to the Android market as soon as i get around to paying the $25 ( Maybe when the HTC magic arrives here in the Netherlands? ).

1 comment: