Category Archives: C#

C#: Project Euler Solution to Problem 27

http://projecteuler.net/problem=27

Considering quadratics of the form:

n² + an + b, where |a| < 1000 and |b| < 1000 where |n| is the modulus/absolute value of n e.g. |11| = 11 and |-4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0.

static void Main(string[] args)
{
    //n² + an + b
    int maxprimes = 0;
    int maxproduct = 0;
    for (int a = 0; a < 1000; a++)
    {
        for (int b = 0; b < 1000; b++)
        {
            int prime = countPrime(a, b);
            if (maxprimes < prime)
            {
                maxprimes = prime;
                maxproduct= (-a*b );
            }
        }
    }
    Console.WriteLine(maxproduct);
}
 
public static int countPrime(int a, int b)
{
    int count = 0;
    int n = 0;
    while (true)
    {
        double result = Math.Pow(n, 2.00) - (a * n) + b;
        if (isPrime((int)result) && result >= 0)
            count++;
        else
            return count;
        n++;
    }
}
 
public static bool isPrime(int n)
{
    if (n == 1)
        return false;
    if (n == 2)
        return true;
    for (int i = 2; i < n; ++i)
    {
        if ((n % i) == 0)
            return false;
    }
    return true;
}

C#: Project Euler Solution to Problem 32

http://projecteuler.net/problem=32

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.

The product 7254 is unusual, as the identity, 39 x 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.

Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.

public static LinkedList<string> onetonine = new LinkedList<string>();
static void Main(string[] args)
{
    LinkedList<int> distinct_product = new LinkedList<int>();
    int product = 0;
    for (int a = 1; a < 2000; a++)
    {
        for (int b = 1; b < 2000; b++)
        {
            product = a * b;
 
            if (isDigits(a + "" + b + "" + product))
            {
                if (!distinct_product.Contains(product) )
                    distinct_product.AddLast(product);
            }
        }
    }
    int sum = 0;
    foreach (int prod in distinct_product)
        sum += prod;
    Console.WriteLine("sum : "+sum);
}
 
public static bool isDigits(string s)
{
    onetonine.Clear();
    onetonine.AddLast("1");
    onetonine.AddLast("2");
    onetonine.AddLast("3");
    onetonine.AddLast("4");
    onetonine.AddLast("5");
    onetonine.AddLast("6");
    onetonine.AddLast("7");
    onetonine.AddLast("8");
    onetonine.AddLast("9");
    if (s.Length != 9)
        return false;
    for (int i = 0; i < s.Length; i++)
    {
        if (onetonine.Contains("" + s[i]))
            onetonine.Remove("" + s[i]);
        else
            return false;
    }
    return true;
}

C#: Project Euler Solution to Problem 39

http://projecteuler.net/problem=39

If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.

{20,48,52}, {24,45,51}, {30,40,50}

For which value of p <= 1000, is the number of solutions maximised?

int Max_P = 0;
int P_position = 0;
for (int p = 1; p < 1000; p++)
{
    int count_p = 0;
    for (int a = 1; a < 500; a++)
    {
        for (int b = 1; b < 500; b++)
        {
            for (int c = 1; c < 500; c++)
            {
                if (  (a + b + c == p) &&
                (Math.Pow(a, 2.00) + Math.Pow(b, 2.00) == Math.Pow(c, 2.00)) )
                    count_p++;
            }
        }
    }
    if (Max_P < count_p)
    {
        Max_P = count_p;
        P_position = p;
    }
}
Console.WriteLine("p = "+P_position);

C#: Project Euler Solution to Problem 47

http://projecteuler.net/problem=47

The first two consecutive numbers to have two distinct prime factors are:

14 = 2 x 7
15 = 3 x 5

Find the first four consecutive integers to have four distinct primes factors. What is the first of these numbers?

static void Main(string[] args)
{
    LinkedList<int> threefactors = new LinkedList<int>();
    int n = 0;
    while (true)
    {
        n++;
        int factcount = 0;
        for (int i = 1; i <= n; i++)
        {
            if (n % i == 0 && isPrime(i))
                factcount++;
        }
        if (factcount == 4)
        {
            threefactors.AddLast(n);
            int lastn = (n - 1);
            int lastn2 = (n - 2);
            int lastn3 = (n - 3);
            if (threefactors.Contains(lastn)  && threefactors.Contains(lastn2) && threefactors.Contains(lastn3))
            {
                Console.WriteLine(n);
                Console.WriteLine(lastn);
                Console.WriteLine(lastn2);
                Console.WriteLine(lastn3);
                break;
            }
        }
    }
}
public static bool isPrime(int n)
{
    if (n == 1)
        return false;
    if (n == 2)
        return true;
    for (int i = 2; i < n; ++i)
    {
        if ((n % i) == 0)
            return false;
    }
    return true;
}

C#: Project Euler Solutions to Problems 9, 13, and 38

For solving ten consecutive problems (1-10).

http://projecteuler.net/problem=9

a2 + b2 = c2

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

for (int a = 1; a < 1000; a++)
{
    for (int b = 1; b < 1000; b++)
    {
        double a_pow2 = Math.Pow(a, 2);
        double b_pow2 = Math.Pow(b, 2);
        double c_root = Math.Sqrt(a_pow2 + b_pow2);
        if ((a + b + c_root) == 1000.00)
        {
            Console.WriteLine("a "+a+" b "+b+" c "+c_root+" product : "+(a * b * c_root));
            break;
        }
    }
}

http://projecteuler.net/problem=13

Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.

string[] linerows = totalstring.Split('\n');
long sum = 0;
foreach (string row in linerows)
{
    // Console.WriteLine(row);
    string longnum = row;
    string num11 = longnum.Substring(0, 11);
    long num = long.Parse(num11);
    sum += num;
}
Console.WriteLine(sum.ToString().Substring(0, 10));

http://projecteuler.net/problem=38

What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, … , n) where n 1?

static void Main(string[] args)
{
    int number = 0;
    int numberofappend = 2;
    int max = 0;
    while (true)
    {
        number++;
        string catstring = appendmore(number, numberofappend);
        if (catstring.Length > 9)
        {
            number = 0;
            numberofappend++;
        }
        else if  (catstring.Length == 9 && Order(catstring))
        {
            int catint = int.Parse(catstring);
            if (max < catint)
            {
                max = catint;
                Console.WriteLine("max so far : "+ max);
            }
        }
    }
}
public static string appendmore(int num, int howmany)
{
    string cat = "";
    for (int i = 1; i <= howmany; i++)
        cat += "" + num * i;
    return cat;
}
public static bool Order(string n)
{
    string mynum = "" + n;
    int[] int_array = new int[mynum.Length];
    for (int i = 0; i < mynum.Length; i++)
    {
        int_array[i] = int.Parse(mynum[i].ToString());
    }
    Array.Sort(int_array);
    if (int_array[0] == 1)
    {
        int count = 2;
        for (int j = 1; j < int_array.Length; j++)
        {
            if (count == int_array[j])
                count++;
            else
                return false;
        }
    }
    else
        return false;
    return true;
}

C#: Project Euler Solutions to Problems 12 and 41

I have completed 25 Project Euler Questions without cheating. I was awarded a badge that looks like this.

http://projecteuler.net/problem=12

What is the value of the first triangle number to have over five hundred divisors?

int max = 0;
int n = 1;
while(true)
{
    double value = (.5 * n) * (n + 1);
    int devisor_count = 0;
    for (int i = 1; i <= value; i++)
    {
        if (value % i == 0)
            devisor_count++;
    }
    if (max < devisor_count)
    {
        max = devisor_count;
        Console.WriteLine(n + " value  " + value + " devisor Count :" + devisor_count);
    }
    if (devisor_count > 500)
    {
        Console.WriteLine(n + " value  " + value + " FINAL  devisor Count :" + devisor_count);
        break;
    }
    n++;
}

http://projecteuler.net/problem=41

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.

What is the largest n-digit pandigital prime that exists?

static void Main(string[] args)
{
    int n = 1;
    while (true)
    {
        if (isPrime(n))
        {
            if (Order(n))
                Console.WriteLine(n);
        }
        n++;
    }
}
 
public static bool Order(int n)
{
    string mynum = ""+n;
    int [] int_array = new int[mynum.Length];
    for (int i = 0; i < mynum.Length; i++)
        int_array[i] = int.Parse(mynum[i].ToString());
    Array.Sort(int_array);
    if (int_array[0] == 1)
    {
        int count = 2;
        for (int j = 1; j < int_array.Length; j++)
        {
            if (count == int_array[j])
                count++;
            else 
                return false; 
        }
    }
    else
        return false;
    return true;
}
 
public static bool isPrime(int n)
{
    if (n == 1)
        return false;
    if (n == 2)
        return true;
    for (int i = 2; i < n; ++i)
    {
        if ((n % i) == 0)
            return false;
    }
    return true;
}

C#: Project Euler Solution to Problem 42

http://projecteuler.net/problem=42

The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, …

Using words.txt, a 16K text file containing nearly two-thousand common English words, how many are triangle words?

//get a list of 100 triangle numbers
LinkedList<double> tri_nums = new LinkedList<double>();
for( int n = 1; n<101 ; n++)
{
    double value = (.5 * n) * (n + 1);
    tri_nums.AddLast(value);
}
//evaluate word values and compare
StreamReader nameStream;
string fullBook = "";
nameStream = File.OpenText("C:\\Euler\\words.txt");
fullBook = nameStream.ReadToEnd();
nameStream.Close();
string[] names = fullBook.Split(',');
int tri_count = 0;
for (int i = 0; i < names.Length; i++)
{
    int namePosition = (i + 1);
    string name1 = names[i].Replace('"', ' ').Trim();
    int letter_sum = 0;
    for (int j = 0; j < name1.Length; j++)
        letter_sum += (int)(name1[j] - 64);
    if (tri_nums.Contains(letter_sum))
    {
        Console.WriteLine("triangle Word : " +  name1 );
        tri_count++;
    }
}
Console.WriteLine();
Console.WriteLine("Triangle word count : " + tri_count);

C#: Project Euler Solutions to Problems 21 and 52

http://projecteuler.net/problem=21

Evaluate the sum of all the amicable numbers under 10000.

int totalsum = 0;
for (int num = 1; num < 10000; num++)
{
    int tempsum = 0;
    for (int i = 1; i < num; i++)
    {
        if (num % i == 0)
            tempsum += i;
    }
    int secondtempsum = 0;
    for (int i = 1; i < tempsum; i++)
    {
        if (tempsum % i == 0)
            secondtempsum += i;
    }
    if (secondtempsum == num && num !=tempsum)
    {
        Console.WriteLine("amicable pair  " + num + " , " + tempsum );
        totalsum += num;
    }
}
Console.WriteLine(" Final sum : "+totalsum);

http://projecteuler.net/problem=52

It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.

Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.

static void Main(string[] args)
{
    long count = 1;
    while (true)
    {
        long initnum = count;
        long t2 = initnum * 2;
        long t3 = initnum * 3;
        long t4 = initnum * 4;
        long t5 = initnum * 5;
        long t6 = initnum * 6;
        if (compareNums(initnum, t2) && 
            compareNums(initnum, t3) && 
            compareNums(initnum, t4) && 
            compareNums(initnum, t5) && 
            compareNums(initnum, t6))
        {
            Console.WriteLine(initnum);
            break;
        }
        count++;
    }
}
 
public static bool compareNums(long a, long b)
{
    string initstring = "" + a;
    string doublestring = "" + b;
    bool found = false;
    foreach (char digit in doublestring)
    {
        foreach (char innerchar in initstring)
        {
            if (innerchar == digit)
                found = true;
        }
        if (!found)
            return false;
        found = false;
    }
    return true;
}

C#: Project Euler Solution to Problem 92

http://projecteuler.net/problem=92

Problem 92

A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.

For example,

44 – 32 – 13 – 10 – 1 – 1
85 – 89 – 145 – 42 – 20 – 4 – 16 – 37 – 58- 89

Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.

How many starting numbers below ten million will arrive at 89?

static void Main(string[] args)
{
    DateTime dt1 = DateTime.Now;
    int count89 = 0;
    for (int j = 1; j < 10000000; j++)
    {
        double currentNum = j;
        while (true)
        {
            double returnedSum = getNextNum(currentNum);
            currentNum = returnedSum;
            if (returnedSum == 1)
                break;
            if (returnedSum == 89)
            {
                count89++;
                break;
            }
        }
    }
    Console.WriteLine("Chains that end in 89 : "+count89);
    DateTime dt2 = DateTime.Now;
    Console.WriteLine("time "+ (dt2-dt1));
}
public static double getNextNum(double num)
{
    double sum = 0;
    string currentNum = "" + num;
    for (int i = 0; i < currentNum.Length; i++)
    {
        double numSquare = int.Parse(currentNum[i].ToString());
        sum += Math.Pow(numSquare, 2.00);
    }
    return sum;
}

C#: Project Euler Solution to Problem 54

Another fun Project Euler Problem, Number 54. Poker Problem!

http://projecteuler.net/problem=54

In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:

High Card: Highest value card.
One Pair: Two cards of the same value.
Two Pairs: Two different pairs.
Three of a Kind: Three cards of the same value.
Straight: All cards are consecutive values.
Flush: All cards of the same suit.
Full House: Three of a kind and a pair.
Four of a Kind: Four cards of the same value.
Straight Flush: All cards are consecutive values of same suit.
Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.

The cards are valued in the order:
2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.

If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives (see example 1 below). But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared (see example 4 below); if the highest cards tie then the next highest cards are compared, and so on.

The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1’s cards and the last five are Player 2’s cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player’s hand is in no specific order, and in each hand there is a clear winner.

How many hands does Player 1 win?

Although the below c# solution will get you the answer to the Euler Problem, it is still incomplete, and needs extra logic to score between high ranking hands.

Continue reading