Search This Blog

Wednesday, December 29, 2010

Euler problem 41

Last one for today… this isn’t fast code but works…

A bit of a speed up implemented by only checking those which are of length equal to their max character… so there’s not point checking 17 as it’s 2 in length.. so max permitted would be 12… however 132 is fine as it’s 3 in length and has a 3 in it!

_______________________

static void Main(string[] args)
        {
            long max=0;

            for (long i = 1; i < 987654321; i++)
            {
                int len = i.ToString().Length;

               //find max char
                int maxchar = 0;
                foreach (char c in i.ToString())
                {
                    if (c - 48 > maxchar)
                    {
                        maxchar = c - 48;
                    }
                }

               //only check if this could be pandigital - by checking max char and len
                //eg1 17 can't be pandigital as only 2 chars long (eg2 12 =OK, 13=not)

                string s = i.ToString();
                if (maxchar == len && isprime(i))
                {
                 if (s.Split('1').Length==2 && s.Split('2').Length==2 )
                 {
                    if (i.ToString().Length==2 && i > max) {max=i;}
                   
                     if  (s.Split('3').Length==2)
                     {
                         if (i.ToString().Length==3 && i > max) {max=i;}
                         if (s.Split('4').Length==2)
                         {
                             if (i.ToString().Length==4 && i > max) {max=i;}
                              if (s.Split('5').Length==2)
                              {
                                  if (i.ToString().Length==5 && i > max) {max=i;}
                                  if (s.Split('6').Length==2)
                                  {
                                      if (i.ToString().Length==6 && i > max) {max=i;}
                                       if (s.Split('7').Length==2)
                                       {
                                           if (i.ToString().Length==7 && i > max) {max=i;}
                                           if (s.Split('8').Length == 2)
                                           {
                                               if (i.ToString().Length == 8 && i > max) { max = i; }
                                               if (s.Split('9').Length == 2)
                                               {
                                                   if (i.ToString().Length == 9 && i > max) { max = i; }
                                                   break;
                                               }
                                           }
                                       }
                                  }
                              }
                         }
                     }
                 }
                }
            }
            Console.WriteLine(max);
            Console.ReadLine();

        }

 

static bool isprime(long n)
       {
           if (n == 2 || n == 3 || n == 5) { return true; }

          if (n%2==0) {return false;}
          if (n%3 == 0) { return false;}
          if (n%5 == 0) { return false;}

          for (int t = 7; t < Math.Sqrt(n); t++)
          {
              if (n % t== 0)
              {
                  return false;
              }
          }

          return true;

       }

Euler Problem 40

Brute force attack!!!

Keep making the string longer until you hit 1 million chars long.. then do the calc they want.. rem first place is s[0]…. and you’re sorted!

____

static void Main(string[] args)
{
    string s = "";
    int i=0;
    while (s.Length<1000001)
   {
       i++;
        s += i.ToString();
    }

    int sum = (Convert.ToInt32(s[0])-48) * (Convert.ToInt32(s[9])-48) * (Convert.ToInt32(s[99])-48) * (Convert.ToInt32(s[999])-48) * (Convert.ToInt32(s[9999])-48) * (Convert.ToInt32(s[99999])-48) * (Convert.ToInt32(s[999999])-48);
   
 
    Console.WriteLine("Answer>>"+sum);
    Console.ReadLine();

}

Euler Problem 39

An easier one… some geometry and Pythog theroem..

I just made a big array, used that as a counter for each solution.. then scanned it to find the answer.

Just remember that the counter is not for c(the hyp) but for the perimeter length (p=a+b+c)…. !

____________

static void Main(string[] args)
       {
           int[] cc = new int[1001];  //somewhere to store the counts

           for (int a = 1; a < 999; a++)
           {
               for (int b = 1; b < 999; b++)
               {
                   double c = Math.Sqrt(a * a + b * b);

                   if (c%1==0 && (a+b+c <= 1000))  //must be int length sides and per<=1000
                   {
                      
                       cc[Convert.ToInt32(a+b+c)]++;
                   }
               }
           }
           //now find largest value
           int maxp = 0;
           int maxn = 0;
           for (int i = 0; i < 1000; i++)
           {
               if (cc[i] > maxn)
               {
                   maxn = cc[i];
                   maxp = i;
               }
           }

           Console.WriteLine("Answer>>"+maxp + " count of "+maxn);
           Console.ReadLine();

       }

Euler Problem 38

So here you need to do some pandigital checks again like problem 32…

We know the answer must be bigger than that given in the example.. as I tried putting their example answer in to see if it was the answer they were after.. but no…! Anyway this means the final value is somewhere between 91873654 and 987654321… so that’s a start.

I was thinking the number of parts to split up the 9 digit number into may be 2,3,4.. as in 123,456789 would be 2 parts.. but to be a correct value then part 1 x 2 should equal part 2… (not here obviously as 123 * 2 = 246)…

My plan was to try this with 2 parts.. and if it didn’t work then look at 3 parts.. and so on.. but I ran it with 2 parts and got the answer so didn’t need to go any further than this!!

Not the smartest, or most elegant solution… but it did the job..

____________________

static void Main(string[] args)
{
//must be bigger than 918273654 as it's mentioned in question
//and I tested it as the answer and it wasn't..
for (int i = 987654321; i > 918273645; i--)
{
string s = i.ToString();

//contains 1-9 once - pandigital 9
if (
s.Split('1').Length == 2 &&
s.Split('2').Length == 2 &&
s.Split('3').Length == 2 &&
s.Split('4').Length == 2 &&
s.Split('5').Length == 2 &&
s.Split('6').Length == 2 &&
s.Split('7').Length == 2 &&
s.Split('8').Length == 2 &&
s.Split('9').Length == 2)
{

//check case of 2 parts
for (int n=1;n<9;n++)
{
int part1 = Convert.ToInt32(i.ToString().Substring(0,n));
int part2= Convert.ToInt32(i.ToString().Substring(n,i.ToString().Length-n));

if (part2==part1*2)
{
Console.WriteLine(i);
goto foo;
}

}

}//end of pandigital check
}


foo:
Console.WriteLine("Done!");
Console.ReadLine();

}

Euler Problem 37

http://projecteuler.net/index.php?section=problems&id=37

The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.

Find the sum of the only eleven primes that are both truncatable from left to right and right to left.

NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.

______

so the first thing I did wrong was to consider 1 to be a prime.. once I’d sorted that out I got this list.. which is 11 primes…  so those must be what they’re after!

23
37
53
73
313
317
373
797
3137
3797
739397

_________________

 

static void Main(string[] args)
       {
           long sum = 0;
           int found = 0;
           long i = 11;
           while (found<11)
           {
              int c=0;
              i++;
              int l = i.ToString().Length;

              for (int x = 0; x < l; x++)
              {

                  long t1 = Convert.ToInt64(i.ToString().Substring(x, l - x));
                  long t2 = Convert.ToInt64(i.ToString().Substring(0, x+1));

                  if (isprime(t1) && isprime(t2) && t1 != 1 && t2 != 1 )
                  {
                      c++;
                  }
                  else
                  {
                      c = 0;
                  }

              }
              
               if (c == i.ToString().Length)
                   {
                       sum += i;
                       found++;
                       Console.WriteLine(i);
                   }

           }

           Console.WriteLine("Answer>>>"+sum);
           Console.ReadLine();

       }

static bool isprime(long n)
       {
           if (n == 2 || n == 3 || n == 5) { return true; }

          if (n%2==0) {return false;}
          if (n%3 == 0) { return false;}
          if (n%5 == 0) { return false;}

          for (int t = 7; t < Math.Sqrt(n); t++)
          {
              if (n % t== 0)
              {
                  return false;
              }
          }

          return true;

       }

Euler Problem 36

Just count from 1 to n, find equivalent binary, check both base 10 and base 2 values are palindromic.. job done!

Interestingly in .NET to turn binary into base 10 then just do this!

Convert.ToInt32("1001",2)    

1001 ==>> 9

________________

 

static void Main(string[] args)
       {
           int counter = 0;
           int sum = 0;

           for (int i = 1; i < 1000000; i++)
           {
               string binary = IntToString(i, new char[] { '0', '1' });

               if (palindromic(i.ToString()) && palindromic(binary))
               {
                   sum += i;
               }

           }

           Console.WriteLine(sum);
           Console.ReadLine();

       }


       static bool palindromic(string s)
       {
           string rev="";
           for (int i = s.Length;i>0;i--)
           {
               rev += s.Substring(i-1,1);
           }

           if (s == rev)
           {
               return true;
           }

           return false;

       }

Tuesday, December 28, 2010

Euler Problem 35

Fairly straight forward this one…

________________

static void Main(string[] args)
        {
            int counter = 0;

            for (long i = 2; i < 1000000; i++)
            {
                string s = i.ToString();
                int l= s.ToString().Length;

                int c = 0;

                for (int x = 0; x <l; x++)
                {
                    string sr = s.Substring(x, l - x) + s.Substring(0,x);
                    if (!isprime(Convert.ToInt32(sr)))
                    {
                        break;
                    }
                    else
                    {
                        c++;
                    }


                }

                if (c==l) {
                    counter++;}


            }

            Console.WriteLine(counter);
            Console.ReadLine();

        }

 

static bool isprime(int n)
       {
           if (n == 2 || n == 3 || n == 5) { return true; }

          if (n%2==0) {return false;}
          if (n%3 == 0) { return false;}
          if (n%5 == 0) { return false;}

          for (int t = 7; t < Math.Sqrt(n); t++)
          {
              if (n % t== 0)
              {
                  return false;
              }
          }

          return true;

       }

Euler Problem 34

This was an easy one.. at last!

http://projecteuler.net/index.php?section=problems&id=34

______________________

static void Main(string[] args)
       {

           long bigsum = 0;

           for (long i = 3; i < 1000000; i++)
           {
               string s = i.ToString();
               long sum = 0;
               foreach (char c in s)  //split up to chars
               {
                  sum+= factorial(c-48);   //convert from ASCII to numerical value of char (c)
                  if (sum > i) { break; }
               }

               if (sum == i) {bigsum += sum;
               }

           }

           Console.WriteLine(bigsum);
           Console.ReadLine();

       }

static long factorial(long n)
        {
            long tot = 1;
            for (long i = 1; i < n+1; i++)
            {
                tot *= i;

            }
            return tot;
        }

Euler Problem 33

I found this puzzle quite tricky to understand… perhaps the question could be written more clearly…

Essentially you just need to find all the fractions which have no more than 2 digits in top/bottom (ie <99/99), which are equal to <1, and which have the same number in the top and bottom which when that number is removed from the fraction the result is the same as the full fraction… anything using factors of 10 is ignored.

So 10/20 = 1/2 (remove 0 from top and base) – but this simple example is ignored.. they only want more complex ones like…

16/64 = 0.25 … remove those common 6s and you’d have 1/4 which is also 0.25 so this what they’re after…! In fact you now only need find the other 3!

I did it by using MOD10 to get the last number, and (Convert.ToInt16(t/10)) to get the first… then just compare these to find when numbers match… could be done using string conversions otherwise..

_______________________

static void Main(string[] args)
{
double sum = 1;

for (int b = 1; b < 100; b++) //t/b has to be <1
{
for (int t = 1; t < b; t++) //only check up to 99/98
{
double f= Convert.ToDouble(t) / Convert.ToSingle(b);
double i= Convert.ToDouble(Convert.ToInt16(t/10));
double j= Convert.ToDouble(Convert.ToInt16(b/10));
double x = 0;

//skip easy ones that divide by 10 top and bottom
if ( (t%10!=0 && b%10!=0))
{
//(i == j || i == b % 10 || t % 10 == j || t % 10 == b % 10) )

if (i == j) { x = (t % 10) / (b % 10); }
if (i == b%10) { x = (t % 10) / j; }
if (t%10 == j) { x = i / (b % 10); }
if (t%10 == b%10) { x = i / j; }

if (x == f)
{
sum *= f;
Console.WriteLine(t + "/" + b);
}

}
}
}

Console.WriteLine("Answer>>" + 1/sum);
Console.ReadLine();

}

Monday, December 27, 2010

Euler Problem 32

Been on hols… so mini break from this.. but had the chance to do one more…

Here we need to find the sum of all products which use numbers 1-9 ONCE in being formed from 2 multipliers and the product itself…

e.g.  4 x 1738 = 6952    => uses 1,2,3,4,5,6,7,8,9

Note we should only include each product (eg 6952) once in the final sum… so I used a list for this.

Other tips – the product and multipliers can be formed into a string.. whose length must be 9.. anything else would mean a double or missing value.

Also we only need test up to 9876 (we could do 9999 but it’d be pointless as there are repeated values there already!)

_________________________

static void Main(string[] args)
       {

           BigInteger sum = 0;
           List<long> found = new List<long>();

           for (long a = 1; a < 9876; a++)
           {
               for (long b = 1; b < 9876; b++)
               {
                   long c = a * b;
                   if (contains1to9once(a, b, c))
                   {
                       if (!found.Contains(c))
                       {
                           sum += c;
                           found.Add(c);
                       }
                   }
               }
           }
           Console.WriteLine(sum);
           Console.ReadLine();

       }

       static bool contains1to9once(long a, long b, long c)
       {
           string s = a.ToString() + b.ToString() + c.ToString();
       
           //has to be 9 chars long only with one of each
           if(s.Length==9 &&
           s.Split('1').Length==2 &&
           s.Split('2').Length==2 &&
           s.Split('3').Length==2 &&
           s.Split('4').Length==2 &&
           s.Split('5').Length==2 &&
           s.Split('6').Length==2 &&
           s.Split('7').Length==2 &&
           s.Split('8').Length==2 &&
           s.Split('9').Length==2)
           {

               return true;
           }
           return false;


       }

Sunday, December 19, 2010

Euler Problem 31

How many ways using UK coins (1,2,5,10,20,50,100,200) can you make 200p?

I just used loops for each coin type.. not very fast but does the trick..

______

static void Main(string[] args)
        {
            int c = 1; //2 dollar coin = one way

            for (int p1 = 0; p1 < 201; p1++)
            {
                for (int p2 = 0; p2 < 201; p2 += 2)
                {
                    for (int p5 = 0; p5 < 201; p5 += 5)
                    {
                        for (int p10 = 0; p10 < 201; p10 += 10)
                        {
                            for (int p20 = 0; p20 < 201; p20 += 20)
                            {
                                for (int p50 = 0; p50 < 201; p50 += 50)
                                {
                                    for (int p100 = 0; p100 < 201; p100 += 100)
                                    {
                                        if (p1 + +p2 + p5 + p10 + p20 + p50 + p100 == 200)
                                        {
                                            c++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Console.WriteLine(c);

             Console.ReadLine();

        }

Euler Problem 30

Iterate.. split up to sep characters… power of 5 to each.. sum… is it equal to the current iteration variable.. if so.. add to the big sum.. repeat…

http://projecteuler.net/index.php?section=problems&id=30

____________

static void Main(string[] args)
        {
            int bigsum = 0;

            for (int i = 2; i < 10000000; i++)
            {

                string s = i.ToString();
                int sum = 0;

                for (int x=0;x<s.Length;x++)
                {
                    int c = Convert.ToInt32( s.Substring(x, 1));

                    sum += Convert.ToInt32(Math.Pow(c,5));
                }

                if (sum == i)
                {
                    Console.WriteLine(i);
                    bigsum += sum;
                }


            }

            Console.WriteLine(">> "+bigsum);
             Console.ReadLine();

        }

Saturday, December 18, 2010

Euler Problem 29

http://projecteuler.net/index.php?section=problems&id=29

This is easy … IF… you can handle big numbers…. which is possible in .Net4.. or.. using a BigInteger class..

I used the CodeProject class from Chew Keong TAN

http://www.codeproject.com/KB/cs/biginteger.aspx

then ran the simple iteration as follows…

__________________

static void Main(string[] args)
       {
          
           List<BigInteger> ans = new List<BigInteger>();

           for (int a = 2; a < 101; a++)
           {
               for (int b = 2; b < 101; b++)
               {

                   BigInteger bg = pow(a, b);

                   if (!ans.Contains(bg))
                   {
                       ans.Add(bg);
                   }

               }


           }

           Console.WriteLine(ans.Count);

            Console.ReadLine();

       }


       static BigInteger pow(int a, int b)
       {
           BigInteger res = 1;

           for (int t = 1; t < b+1; t++)
           {
               res *= a;
           }

           return res;
       }

Euler Problem 28

Hmmm.. so a spiral… going out from the centre…

Well this isn’t the smoothest solution but I noticed the following from the example given:

21 22 23 24 25
20  7  8  9 10
19  6  1  2 11
18  5  4  3 12
17 16 15 14 13

the numbers from the 4 diagonals are:

1,9,25     1,3,13      1,5,17    1,7,21

So I added another lap around the square and found the intervals between numbers were:

1,9,25,49     1,3,13,31      1,5,17,37    1,7,21,43
8  16   24          2  10  18        4 12  20      6  14  22
   8   8               8   8              8   8            8   8 

Hmmmm.. so.. the first diagonal (1,9,25) just goes up in multiples of 8… and so do the others but from different starting points.

So I just made an app which cycled thru building the numbers for each diagonal and adding to a list.. then pull them in order from the list and calc the sum! The only thing to remember is that in the sum you should only count the 1 in the centre a single time.. so I just did a –3… found this out from testing it against their example of a 5x5 square.

Oh and the other thing is when to stop adding… so I just determined this by going until the max value in the first diagonal reached the square of the size…

Like I said.. a bit messy.. but got me the answer first time!

________

static void Main(string[] args)
       {
           int size=  1001;
           long d1 = 1;
           long d2 = 3;
           long d3 = 5;
           long d4 = 7;
           int i = 0;
           long offsetd2 = 2;
           long offsetd3 = 4;
           long offsetd4 = 6;

           List<long> l1 = new List<long>();
           List<long> l2 = new List<long>();
           List<long> l3 = new List<long>();
           List<long> l4 = new List<long>();

           l2.Add(1);
           l2.Add(3);
           l3.Add(1);
           l3.Add(5);
           l4.Add(1);
           l4.Add(7);

           while (d1<((size*size)+1))
           {
               offsetd2 += 8;
               offsetd3 += 8;
               offsetd4 += 8;

               d1 += 8 * i;
               d2 += offsetd2;
               d3 += offsetd3;
               d4 += offsetd4;

               l1.Add(d1);
               l2.Add(d2);
               l3.Add(d3);
               l4.Add(d4);

         
           i++;
           }

           //sort out starting positions

          long sum = 0;

           for (int w = 0; w < (i-1); w++)
           {
               sum += l1[w] + l2[w] + l3[w] + l4[w];
           }

           Console.WriteLine(sum-3);  //1 is only counted on one of the diagonals so -3 from total

            Console.ReadLine();

       }

Euler Problem 27

Requires… a prime number solver… done that earlier.. so.. actually quite an easy problem..

static void Main(string[] args)
{

     // n² + an + b,
     int max = 0;
     int maxx = 0;

     for (int a = -1000; a < 1000; a++)
     {

         for (int b = -1000; b < 1000; b++)
         {
             max = 0;

             for (int n = 0; n < 500; n++)  //number of primes in a row
             {
                int p= (n * n) + (a * n) + b;
                
                 if (isprime(p) && p> 1)
                 {
                     max++;

                     if (max > maxx)
                     {
                         maxx = max;
                       
                         Console.WriteLine(a + "," + b + "," + maxx);
                     }
                 }
                 else
                 {
                     max = 0;
                     break;
                  
                 }
             }
         }

     }

      Console.ReadLine();

}

Euler Problem 9

Did this a while ago but didn’t post… so here it is…

 

static void Main(string[] args)
       {

           for (int a = 1; a < 100000; a++)
           {
               for (int b = a; b < 100000; b++)
               {

                   double c = Math.Sqrt((a*a)+(b*b));
                   if (a + b + c == 1000)
                   {
                       Console.WriteLine(a + "," + b + "," + c);
                       Console.WriteLine(a * b * c);
                   }

               }


           }

       }

Friday, December 17, 2010

Euler Problem 26

Difficult!!

http://projecteuler.net/index.php?section=problems&id=26

Needed help with this one.. from here … thanks!!

http://universequeen.org/archives/133

____________________

 

static void Main(string[] args)
        {
           
            int max=0;
            int max_d=0;

            for (int d=2;d<1000;d++)
            {
                 double s = 1f/Convert.ToDouble(d);
               
                int l = reclencycle(d);

                if (l> max)
                {
                    max=l;
                    max_d=d;
                }

            }

            Console.WriteLine(max_d);
            Console.ReadLine();

        }

 

        static int reclencycle(int n)
        {
         
        int[] q = new int[1000];
        int[] r = new int[1000];
 
        r[0] = 1;
        q[0] = 0;
 
        for( int i=1; i<1000; i++ )
        {
            q[i] = r[i-1]*10/n;
            r[i] = r[i-1]*10 - q[i]*n;
 
            for( int j=1; j<i; j++ )
            {
                if( q[j] == q[i] && r[j] == r[i] )
                {
                    return (i-j);
                }
            }
 
        }
 
        return 0;
    }

Thursday, December 16, 2010

Euler Problem 25

Ahh.. back to good old problem 16 again.. and adapt the code…

http://projecteuler.net/index.php?section=problems&id=25

_______________

           int[] c = new int[1000];
            int[] d = new int[1000];
            int[] e = new int[1000];

            c[0] = 1; //starting condition
            d[0] = 1;
            e[0] = 0;

            int counter = 2;// starts with 1,1,.. needs to be offset in count so F12=144

            while (c[999]==0) 
            {

                counter++;
                //do mult in place
                for (int n = 0; n < 1000; n++)
                {
                    e[n] = d[n];
                    d[n] = c[n];
                    c[n] = c[n]+e[n];

                }


                //sort out carries across to right
                for (int n = 0; n < 999; n++)
                {
                    while (c[n] > 9)
                    {
                        if (c[n] >= 10)
                        {
                            c[n + 1] += 1;
                            c[n] -= 10;
                        }
                    }

                    while (d[n] > 9)
                    {
                        if (d[n] >= 10)
                        {
                            d[n + 1] += 1;
                            d[n] -= 10;
                        }
                    }

                    while (e[n] > 9)
                    {
                        if (e[n] >= 10)
                        {
                            e[n + 1] += 1;
                            e[n] -= 10;
                        }
                    }

 

 


                }

            }

Euler Problem 24

 http://projecteuler.net/index.php?section=problems&id=24

A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:

012   021   102   120   201   210

What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?

_______________

Found this one kinda tricky in C#.. but in Python using the powerful itertools module it’s just 2 lines!

import itertools
print [d for d in itertools.permutations(range(10))][999999]

_________________

Euler Problem 23

Abundant numbers… those whose factors summed are greater than the number.

The challenge here is to find all abundant numbers up to 28123, then to find all those numbers which can’t be written as the sum of two abundant numbers.

So 12 is the first abundant number, whose factors add up to 16… making the smallest number with a sum of abundant numbers = 24.

http://projecteuler.net/index.php?section=problems&id=23

This works.. but fairly dumb code…. still .. enough to get me to the next challenge!

_______________

 

static void Main(string[] args)
      {
          List<int> abundantnumbers = new List<int>();

         int sum=0; //non abundant numbers factors

          for (int i=1;i<28123;i++)
          {

              if (i < sumofdivisors(divisors(i)))
              {
                  abundantnumbers.Add(i);
              }
         
          //can i be found using all abundant numbers found so far
              if (!issumofabundantnumners(abundantnumbers, i))
              {
                  sum += i;
              }
             
          }

      Console.WriteLine(sum);
      Console.ReadLine();

      }

      static List<int> divisors(int n)
      {
          List<int> div = new List<int>();
          for (int d = 1; d < n; d++)
          {
              if (n % d == 0) { div.Add(d); }
          }

          return div;

      }


      static int sumofdivisors(List<int> div)
      {
          int sum = 0;

          foreach (int i in div)
          {
              sum += i;
          }

          return sum;

      }


      static bool issumofabundantnumners(List<int> ab, int i)
      {
          foreach (int i1 in ab)
          {

              foreach (int i2 in ab)
              {

                  if (i == (i1 + i2))
                  {
                      return true;
                  }

              }
          }

          return false;

      }

Euler Problem 22

So you download a list of names.. and have to order them.. then calculate a value based on the characters (a-z) and position in the list… EASY! or is it????

Yes it is… C# has all the tools for this… build a list..then sort it.. pretty much job done… the only tip is to remember that the first place in the list (pos=0) is the 1st place in the list!!!

http://projecteuler.net/index.php?section=problems&id=22

______________

static void Main(string[] args)
        {
        List<string> names = new List<string>();
     
        //all names are in 1 line!
        System.IO.StreamReader sr = new System.IO.StreamReader("o:\\names.txt");
           
        foreach (string s in sr.ReadLine().Split(','))
        {
            names.Add(s);
        }

        names.Sort();

        long wordssum=0;

        for (int i = 0; i < names.Count; i++)
        {
            wordssum += wordvalue(names[i]) * (i+1);
        }

        Console.WriteLine(wordssum);
        Console.ReadLine();

        }

    static int wordvalue(string s)
      {
        // a=1 b=2 etc
          int val=0;
         
          foreach (char c in s.ToLower())
          {
              if (c > 96 && c < 123)
              {
                  val += Convert.ToInt16(c) - 96;
              }
          }

          return val;
    }

Wednesday, December 15, 2010

Euler Problem 21

http://projecteuler.net/index.php?section=problems&id=21

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.

___________________

static void Main(string[] args)
    {
        long sumofallpairs = 0;

        for (int n = 1; n < 10000; n++)
        {
            if (isamicablepair(n))
            {
                sumofallpairs +=n;
            }

        }

        Console.WriteLine(sumofallpairs);

 
    Console.ReadLine();

    }


    static bool isamicablepair (int n)
{
    int sum1 = 0;
    int sum2 = 0;

    foreach (int i in divisors(n))
    {
        sum1 += i;
    }

    foreach (int i in divisors(sum1))
    {
        sum2 += i;
    }

    if (n == sum2 && n != sum1)
    {
        return true;
    }
    else
    {
        return false;
    }

}

    static List<int> divisors(int n)
    {
        List<int> div = new List<int>();
        for (int d = 1; d < n; d++)
        {
            if (n % d == 0) { div.Add(d); }
        }

        return div;

    }

Euler Problem 20

Ahhh now this one uses something we built before.. around problem 16 I think… just a slight change needed… job done!! Nice to have an easy one for a change!

Problem = sum the numbers from the answer of 100!

http://projecteuler.net/index.php?section=problems&id=20

_________

 

static void Main(string[] args)
        {
           int[] c = new int[999];

            c[0] = 1; //starting condition

            for (int i = 1; i < 100; i++)   //go to the power of 1000
            {
                //do mult in place
                for (int n = 0; n < 999; n++)
                {
                    c[n] *= i;
                }


                //sort out carries across to right
                for (int n = 0; n < 999; n++)
                {
                    while (c[n]>9)
                    {
                    if (c[n] >= 10)
                    {
                        c[n + 1] += 1;
                        c[n] -= 10;
                    }
                    }
                }

            }

            //now add up all the columns
            long sum = 0;

            for (int n = 0; n < 999; n++)
            {
                sum += c[n];
            }

 

            Console.WriteLine(sum);
        Console.ReadLine();

        }

Euler Problem 19

How many Sundays on the first of the month in the 20th Century from 1 Jan 1901 to 31 Dec 2000?

http://projecteuler.net/index.php?section=problems&id=19

Luckily C# can do this really easily!!

 

static void Main(string[] args)
        {

            int counter=0;
            DateTime d = new DateTime(1901,1,1);
           
            while (d.Year<2001)
            {
                if (d.DayOfWeek == DayOfWeek.Sunday && d.Day == 1)
                {
                    counter++;
                }

               d= d.AddDays(1);
            }

 

        Console.WriteLine(counter);
        Console.ReadLine();

        }

Euler Problem 18

http://projecteuler.net/index.php?section=problems&id=18

OK so a triangle.. of costs.. and you need to find the most expensive way across it… so the best way is to work backwards from all possible endings and calculate the most expensive way to get there.

A simple example

      1

  2    5  

7   3   5 

Ending positions are 7,3,5,6…

To get to 7 we can have arrived from 2 or 5.. the most expensive route would be 5+7=13

To get to 3 we can have either come from 2 or 5.. the most expensive route would be 3+5 = 8..

etc  to get a new triangle of max routes which looks like this..

  11

9  10

7  3  5

 

giving us the answer of 11… for the most expensive path thru the triangle….. so repeat this formula for any size of triangle.. using code as follows:

______________________

 

       static void Main(string[] args)
        {

            int[,] a= new int[15,15];
          

a[0,0]=75;
a[0,1]=95; a[1,1]=64;
a[0,2]=17; a[1,2]=47; a[2,2]=82;
a[0,3]=18; a[1,3]=35; a[2,3]=87; a[3,3]=10;
a[0,4]=20; a[1,4]=04; a[2,4]=82; a[3,4]=47; a[4,4]=65;
a[0,5]=19; a[1,5]=01; a[2,5]=23; a[3,5]=75; a[4,5]=03; a[5,5]=34;
a[0,6]=88; a[1,6]=02; a[2,6]=77; a[3,6]=73; a[4,6]=07; a[5,6]=63; a[6,6]=67;
a[0,7]=99; a[1,7]=65; a[2,7]=04; a[3,7]=28; a[4,7]=06; a[5,7]=16; a[6,7]=70; a[7,7]=92;
a[0,8]=41; a[1,8]=41; a[2,8]=26; a[3,8]=56; a[4,8]=83; a[5,8]=40; a[6,8]=80; a[7,8]=70; a[8,8]=33;
a[0,9]=41; a[1,9]=48; a[2,9]=72; a[3,9]=33; a[4,9]=47; a[5,9]=32; a[6,9]=37; a[7,9]=16; a[8,9]=94; a[9,9]=29;
a[0,10]=53; a[1,10]=71; a[2,10]=44; a[3,10]=65; a[4,10]=25; a[5,10]=43; a[6,10]=91; a[7,10]=52; a[8,10]=97; a[9,10]=51; a[10,10]=14;
a[0,11]=70; a[1,11]=11; a[2,11]=33; a[3,11]=28; a[4,11]=77; a[5,11]=73; a[6,11]=17; a[7,11]=78; a[8,11]=39; a[9,11]=68; a[10,11]=17; a[11,11]=57;
a[0,12]=91; a[1,12]=71; a[2,12]=52; a[3,12]=38; a[4,12]=17; a[5,12]=14; a[6,12]=91; a[7,12]=43; a[8,12]=58; a[9,12]=50; a[10,12]=27; a[11,12]=29; a[12,12]=48;
a[0,13]=63; a[1,13]=66; a[2,13]=04; a[3,13]=68; a[4,13]=89; a[5,13]=53; a[6,13]=67; a[7,13]=30; a[8,13]=73; a[9,13]=16; a[10,13]=69; a[11,13]=87; a[12,13]=40; a[13,13]=31;
a[0,14]=04; a[1,14] = 62; a[2,14] = 98; a[3,14] = 27; a[4,14] = 23; a[5,14] = 09; a[6, 14] = 70; a[7, 14] = 98; a[8, 14] = 73; a[9,14] = 93; a[10, 14] = 38; a[11, 14] = 53; a[12, 14] = 60; a[13, 14] = 04; a[14, 14] = 23;

//start at the last row - work back to top of triangle from all end possibilities
for (int row = 13; row > -1; row--)
{
    //now work thru all the columns
    for (int col = 0; col < 14; col++)
    {
        //find in the row below the max val possible from option1 or option 2 (l or r linked cell)
        if (a[col,row+1] > a[col + 1,row+1])
        {
            a[col,row] = a[col,row+1] + a[col,row];
        }
        else
        {
            a[col,row] = a[col+1, row+1] + a[col,row];
        }

    }


}


        Console.WriteLine(a[0,0]);
        Console.ReadLine();

        }

Tuesday, December 14, 2010

Euler Problem 17

How many letters are used in counting from 1 to 1000 inclusive?

Inc the ands, but not spaces or hyphens!

Full details here: http://projecteuler.net/index.php?section=problems&id=17

the approach here is to work out how many times each sequence occurs.. so there are 900 occurrences of the word “hundred” for example…

In the end the answer is 21,124 characters!

_____

 

static void Main(string[] args)
        {

            string a1 = "onetwothreefourfivesixseveneightnine";
            string b1="teneleventwelvethirteenfourteenfifteensixteenseventeeneighteenninetine";
            string b2 = "twentythirtyfortyfiftysixtyseventyeightyninety";
            string c1 = "hundred";
            string c2 ="and";
            string c3 = "onethousand";


        int ans = (90*a1.Length) + (10*b1.Length) + (100*b2.Length)
                +(c1.Length*900) + (a1.Length*100) + (c3.Length) + (c2.Length*99*9);

        Console.WriteLine(ans);
        Console.ReadLine();

        }

Euler Problem 16

http://projecteuler.net/index.php?section=problems&id=16

What is the sum of all the numbers in the answer from 2^1000?

This is tricky because it’s a big number!

C# .NET3.5 does this…1.0715086071862673E+301
…which means I don’t have all the digits to add up…

As an aside.. here’s what python does when you ask it for 2 to the power 1000…

>>> print pow(2,1000)
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

No problem! Just need to add those up……

Anyway back to C#… how to cope? We need to make an array.. and handle it ourselves like this..:

static void Main(string[] args)
       {
           int[] c = new int[999];

           c[0] = 2; //starting condition

           for (int i = 1; i < 1000; i++)   //go to the power of 1000
           {
               //do mult in place
                for (int n=0;n<999;n++)
               {
                   c[n] *= 2;
               }
              
            
               //sort out carries across to right
               for (int n=0;n<999;n++)
               {
                 
                   if (c[n] >= 10)
                   {
                       c[n+1] += 1;
                       c[n] -= 10;
                   }
                   }

           }

           //now add up all the columns
           long sum = 0;

           for (int n = 0; n < 999; n++)
           {
              sum+= c[n];
           }


           Console.WriteLine(sum);

        
       Console.ReadLine();

       }