이경수 선생님의 수학실험실

Problem 38(Pandigital multiples) 본문

Project Euler

Problem 38(Pandigital multiples)

(이경수) 2019. 6. 15. 12:37

Problem 38(Pandigital multiples)

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?

 

In Python:

import time
import math

def ispandigit(n):
    nList = list(str(n))
    nList.sort()
    for i in range(0, 9):
        if i + 1 != int(nList[i]):
            return False
    return True

def digits(n):
    return int(math.log10(n)) + 1

startTime = time.time()
maximum = 0
for i in range(1, 10 ** 4):
    num = ''
    for n in range(1, 9):
        num = num + str(i * n)
        if digits(int(num)) > 9:
            break
        elif digits(int(num)) == 9 and ispandigit(int(num)) is True:
            if int(num) > maximum:
                maximum = int(num)
print(maximum)
print(time.time() - startTime, "seconds")

Run time: 0.1352832317352295 seconds

 

In Java:

package project_euler31_40;

import java.util.ArrayList;
import java.util.Collections;

public class Euler38 {
	public static Boolean ispandigit(int n) {
		String data[];
		String str = "";
		ArrayList<Integer> nList = new ArrayList<Integer>();
		
		str = Integer.toString(n);
		data = str.split("");
		for (int i = 0; i < data.length; i++) {
			nList.add(Integer.parseInt(data[i]));
		}
		Collections.sort(nList);
		for (int i = 0; i < 9; i++) {
			if (i + 1 != nList.get(i)) {
				return false;
			}
		}
		return true;
	}
	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
		int maximum = 0;
		int nNum = 0;
		String sNum = "";
		for (int i = 0; i < Math.pow(10, 4); i++) {
			sNum = "";
			for (int n = 1; n < 9; n++) {
				sNum = sNum + Integer.toString(i * n);
				if (sNum.length() == 9) {
					nNum = Integer.parseInt(sNum);
					if (ispandigit(nNum) == true) {
						if (nNum > maximum) {
							maximum = nNum;
						}
					}
				}
			}
		}
		System.out.println(maximum);
		long endTime = System.currentTimeMillis();
		System.out.println((double)(endTime - startTime)/(double)1000 + "seconds");
	}
}

Run time: 0.114seconds

 

Solution: 932718654

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

Problem 40(Champernowne's constant)  (0) 2019.06.16
Problem 39(Integer right triangles)  (0) 2019.06.16
Problem 37(Truncatable primes)  (0) 2019.06.06
Problem 36(Double-base palindromes)  (0) 2019.06.06
Problem 35(Circular primes)  (0) 2019.06.04
Comments