Pages

Showing posts with label pandigital. Show all posts
Showing posts with label pandigital. Show all posts

Wednesday, July 13, 2011

Problem #32

Problem link
Solution:
package main

import (
"strconv"
"strings"
)

func main() {
mp := map[int]int{}
for i := 1; i < 200; i++ {
for j := 1; j < 5000; j++ {
if isPandigital(i, j, i*j) {
mp[i*j] = 1
}
}
}
sum := 0
for key, _ := range mp {
sum += key
}
println(sum)
}

func isPandigital(mul1, mul2, result int) bool {
str := strconv.Itoa(mul1) + strconv.Itoa(mul2) + strconv.Itoa(result)
if len(str) != 9 {
return false
}
for i := 1; i < 10; i++ {
if !strings.Contains(str, strconv.Itoa(i)) {
return false
}
}
return true
}



Result: 45228
Time: 0m2.405s

Problem #38

Problem link
Solution:
package main

import (
"strconv"
"strings"
)

func main() {
max := 0
var tmp int
for i := 1; i < 10000; i++ {
str := ""
for j := 1; j < 9 && len(str) < 9; j++ {
str += strconv.Itoa(i * j)
}
if len(str) == 9 && isPandigital(str) {
tmp, _ = strconv.Atoi(str)
if tmp > max {
max = tmp
}
}
}
println(max)
}

func isPandigital(str string) bool {
if len(str) != 9 {
return false
}
for i := 1; i < 10; i++ {
if !strings.Contains(str, strconv.Itoa(i)) {
return false
}
}
return true
}



Result: 932718654
Time: 0m0.049s

Problem #41

Problem link
Solution:
package main

import (
"strconv"
"strings"
)

func main() {
a := make([]bool, 87654322)
a[0], a[1] = true, true
prime := 3
var k int
finished := false
for !finished {
for k = 2 * prime; k < len(a); k += prime {
a[k] = true
}
for k = prime + 2; k < len(a) && a[k]; k += 2 {
}
if k < len(a) {
prime = k
} else {
finished = true
}
}
//a now has false values for the primes and multiples of 2
//but we skip even numbers in our iteration.
for i := int64(87654321); i > 0; i -= 2 {
if !a[i] && isPandigital(i) {
println(i)
return
}
}
}

func isPandigital(in int64) bool {
str := strconv.Itoa64(in)
n := len(str)
for i := 1; i <= n; i++ {
if !strings.Contains(str, strconv.Itoa(i)) {
return false
}
}
return true
}



Result: 7652413
Time: 0m15.596s

Problem #43

Problem link
Solution:
package main

import (
"strconv"
)

var result int64
var divisors []int
var tmp int
var tmp64 int64

func main() {
result = int64(0)
divisors = []int{2, 3, 5, 7, 11, 13, 17}
allPerms("", "0123456789")
println(result)
}

func allPerms(pre, s string) {
if len(s) == 0 {
checkTheProperty(pre)
} else {
for i := 0; i < len(s); i++ {
allPerms(pre+s[i:i+1], s[0:i]+s[i+1:len(s)])
}
}
}

func checkTheProperty(s string) {
if s[0] == '0' {
return
} else {
for i := 1; i < 8; i++ {
if tmp, _ = strconv.Atoi(s[i : i+3]); tmp%divisors[i-1] != 0 {
return
}
}
}
tmp64, _ = strconv.Atoi64(s)
result += tmp64
}



Result: 16695334890
Time: 0m6.223s