CSharp - gregorymorrison/euler1 GitHub Wiki

When C# was originally introduced in 2001, it was criticized as a carbon-copy of Java. But since then, the C# camp has been marching right along in language development, adding all kinds of cool features such as the declarative-styled LINQ.

I haven't worked with .NET before and expected a bit of a learning curve. To start off, I took a C# Hello World example and pasted in my Euler1 Java class. I tried to compile it just to see what it would return. And wouldn't you know it, that sumbitch worked!

// Euler1 in C #
using System;

class Euler1 {
    private int size;
    private int result;

    public Euler1(int size) {
        this.size = size;
    }

    public void solve() {
        result = 0;
        for (int i=0; i<size; i++) {
            if (i%3==0 || i%5==0) {
                result += i;
            }
       }
    }

    public int getResult() {
        return result;
    }

    public static void Main() {
        Euler1 euler1 = new Euler1(1000);
        euler1.solve();
        Console.WriteLine(euler1.getResult());
    }
}

Really, C#? Is there still that little difference between you and your older brother, Java? No, as it turns out. C# has done a lot of modernizing. For instance, they've added a full complement of functional operations - behold, versions of Map, Filter, Fold, and Lambda!

// Euler1 in C #
using System;using System.Linq;
class Euler1 {
    public static void Main() {

        Func<int, int> euler1 = size => {
            return Enumerable.Range(1, size)
                .Select(i => i)
                .Where(i => i%3==0 || i%5==0)
                .Aggregate(0, (i,acc) => i+acc);
        };

        Console.WriteLine(euler1(999));
    }
}

Select() here serves no purpose - it's just added here for illustration. C# even supports closures, yay! LINQ's syntax is really flexible - here's a SQL-flavored version:

// Euler1 in C #
using System;
using System.Linq;

class Euler1 {
    public static void Main() {
        var range = Enumerable.Range(1, 999);

        var result = (from n in range
                     where n % 3 == 0 || n % 5 == 0
                     select n).Sum();

        Console.WriteLine(result);
    }
}

It took me a few hours to write this code. Most of it was a pleasant experience - documentation is great and there is much to explore. Compiler messages seem adequate. Make sure you include the System.Linq declaration - I spent way too much time figuring that out because the many online tutorials I read omitted it, sigh.

A couple blogs I read made me expect a difficult time with Mono. I found it to be a piece of cake, though. I simply used Yum to install mono-basic. Then, I compiled my code with mcs and executed it with mono:

$ mcs euler1.cs
$ mono euler1.exe
233168
⚠️ **GitHub.com Fallback** ⚠️