88
99# Solution by Sam Gerber
1010
11- def pandigital_prime
12- primes = primes ( 987_654_321 )
13- puts "primes done"
14-
15- loop do
16- number = primes . pop
17- digits = number . to_s . length
18- return number if is_pandigital? ( number , digits )
19- end
20- end
11+ # Note: all numbers whose digits sum to a multiple of 3 are divisible by 3.
12+ # The following are the sums of the digits of n-digit pandigital numbers:
13+ # 2-digits: 3 = 1 + 2 DIVISIBLE BY 3!
14+ # 3-digits: 6 = 1 + 2 + 3 DIVISIBLE BY 3!
15+ # 4-digits: 10 = 1 + 2 + 3 + 4 24 possible primes
16+ # 5-digits: 15 = 1 + 2 + 3 + 4 + 5 DIVISIBLE BY 3!
17+ # 6-digits: 21 = 1 + 2 + 3 + 4 + 5 + 6 DIVISIBLE BY 3!
18+ # 7-digits: 28 = 1 + 2 + 3 + 4 + 5 + 6 + 7 5040 possible primes
19+ # 8-digits: 36 = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 DIVISIBLE BY 3!
20+ # 9-digits: 45 = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 DIVISIBLE BY 3!
21+
22+ # With this knowledge, we simply build and sort an array of all possible
23+ # 4- or 7-digit pandigital numbers and beginning at the end, return the
24+ # first prime we find.
2125
26+ def pandigital_prime
27+ pandigitals = [ ]
28+ [ 4 , 3 , 2 , 1 ] . permutation { |p | pandigitals << p . join . to_i }
29+ [ 7 , 6 , 5 , 4 , 3 , 2 , 1 ] . permutation { |p | pandigitals << p . join . to_i }
30+ pandigitals . sort! . reverse!
2231
23- # This method retuns an array of all primes not exceeding max
24- def primes ( max )
25- primes = [ ]
26- number = 2
27-
28- while number <= max
29- primes << number if is_prime? number
30- number += 1
31- end
32- primes
32+ pandigitals . each { |number | return number if is_prime? ( number ) }
3333end
3434
35+
3536# This method returns true if a number is prime
3637def is_prime? ( number )
3738 number = number . abs
@@ -47,11 +48,4 @@ def is_prime?(number)
4748 true
4849end
4950
50- # This method returns true if the numbers contain all the
51- # digits from 1 to n
52- def is_pandigital? ( *numbers , n )
53- numbers = numbers . join . split ( "" ) . sort
54- numbers . count == numbers . uniq . count && numbers . first == "1" && numbers . last == n . to_s
55- end
56-
5751puts pandigital_prime
0 commit comments