2020-09-30

Pandigital Squares

A pandigital number, like 4730825961, is a ten-digit number in which each digit from zero to nine appears exactly once. A square number, like 25² = 625, is a number with an integral square root. Your task is to write a program that finds all of the pandigital square numbers.

下面是嘗試的結果:

#!/usr/bin/env tclsh

set digital [list "0" "1" "2" "3" "4" "5" "6" "7" "8" "9"]

proc is_pandigital {n} {
    set length [string length $n]
    if {$length != 10 } {
        return 0
    }

    foreach mychar $::digital {
        if {[string first $mychar $n] == -1} {
            return 0
        }
    }

    return 1
}

set minvalue [expr int(floor(sqrt(1023456789)))]
set maxvalue [expr int(floor(sqrt(9876543210)))]

for {set n $minvalue} {$n <= $maxvalue} {incr n} {
    set num [expr $n * $n]
    if {[is_pandigital $num]==1} {
         puts $num
    }
}

沒有留言: