2021-06-07

Sum of Squares

You are given a number $N >= 10. Write a script to find out if the given number $N is such that sum of squares of all digits is a perfect square. Print 1 if it is otherwise 0.

#!/usr/bin/tclsh
# You are given a number $N >= 10.
# Write a script to find out if the given number $N is such 
# that sum of squares of all digits is a perfect square.
# Print 1 if it is otherwise 0.

puts -nonewline "Input: "
flush stdout
gets stdin number
if {$number < 10} {
    puts "Number requires >= 10."
    exit
}

set total 0
set mylist [split $number ""]
foreach substring $mylist {
    set result [expr $substring * $substring]
    set total [expr $total + $result]
}

set root [expr int(sqrt($total))]
set check [expr $root * $root]
if {$total==$check} {
    puts "Output: 1"
} else {
    puts "Output: 0"
}

沒有留言: