Project Euler

Project Euler Problem 38

steloflute 2012. 6. 9. 00:08

Problem 38

28 February 2003

Take the number 192 and multiply it by each of 1, 2, and 3:

192 1 = 192
192 2 = 384
192 3 = 576

By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3)

The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5).

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?


Answer:
932718654

C#

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
using System.IO;

namespace Euler {
    class Program {
        static string tryMakePandigital(int n) {
            string r = "";
            for (int i = 1; ; i++) {
                r += (n * i).ToString();
                if (i > 1 && r.Length >= 9) break;
            }
            return r;
        }

        static bool isPandigital(string s) {
            var hs = new HashSet<char>(s);
            if (hs.Contains('0')) return false;
            return hs.Count == s.Length;
        }

        static int pandigital(int n) {
            string s = tryMakePandigital(n);
            int r = 0;
            if (isPandigital(s)) {
                return Convert.ToInt32(s);
            } else
                return 0;
        }

        static void Main(string[] args) {
            Console.WriteLine(Enumerable.Range(1, 99999).Select(pandigital).Max());            
        }
    }
}



'Project Euler' 카테고리의 다른 글

Project Euler Problem 40  (0) 2012.06.09
Project Euler Problem 39  (0) 2012.06.09
Project Euler Problem 37  (0) 2012.06.09
Project Euler Problem 36  (0) 2012.06.09
Project Euler Problem 35  (0) 2012.06.09