Sunday, October 27, 2013

Problem 26 - resolved in C#

I started trying to solve the problem that I am up to, problem 57, in C#, as I realized it was a pretty nice language that I had yet to use. However, I soon discovered that I had chosen the wrong language. After struggling with trying to write a rational class and then even contemplating writing my own BigInteger class, I realized that I knew that there was a better way to solve problem 57, and that was with Racket. More on that in the next post, this post just has my fairly unexciting C# code, which is actually (I think, very subjectively) cleaner than the Racket I originally wrote to solve problem 26 (which involves finding the denominator d < 1000 such that 1 / d has the largest cycle).
public class Euler26 {

    public static int biggestCycle(int d) {
        int[] rems = new int[1000];
        int r = 1;
        int i = 0;
        while (r != 0) {
            r = (r * 10) % d;
            for (int j = 0; j < i; ++j) {
                if (rems[j] == r) {
                    return i;
                }
            }
            rems[i++] = r;
        }
        return i;
    }

    public static int Main(string[] args) {
        int ans = 0;
        for (int d = 1; d < 1000; ++d) {
            ans = ans < biggestCycle(d) ? d : ans;
        }
        System.Console.WriteLine(ans);
        return 0;
    }
}

No comments:

Post a Comment