Sequence and squares
Weekly challenge 116 — 7 June 2021
Week 116: 7 Jun 2021
You are given a number $N >= 10.
Write a script to find out if the given number is such that sum of the squares of all its digits is a perfect square. Print 1 if it is otherwise 0.
Example 1 Input: $N = 34 Output: 1 as 3^2 + 4^2 => 9 + 16 => 25 => 5^2 Input: $N = 50 Output: 1 as 5^2 + 0^2 => 25 + 0 => 25 => 5^2 Input: $N = 52 Output: 0 as 5^2 + 2^2 => 25 + 4 => 29
This is more-or-less explained in the task description:
Such numbers are not sparse, though ones containing no repeats and no zeroes - like 12379 - are few and far between.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2021-06-07 use utf8; # Week 116 - task 2 - Sum of squares use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; sum_of_squares(34); sum_of_squares(52); sum_of_squares(926); sum_of_squares(9539); sum_of_squares(12379); sub sum_of_squares { my ($n, $squared, $is_good, $explain); # initialise $n = $_[0]; # calculate sum of squares for (split('', $n)) { $squared += $_ ** 2; $explain .= qq[$_² + ]; } # test for squareness $is_good = sqrt($squared) == int(sqrt($squared)); # report $explain =~ s|\+ $|= |; say qq[\nInput: $n]; say qq[Output: ] . ($is_good ? qq[1 ∵ $explain] . sqrt($squared) . q[²] : '0'); }
last updated 2026-03-24 — 10 lines of code
Input: 34 Output: 1 ∵ 3² + 4² = 5² Input: 52 Output: 0 Input: 926 Output: 1 ∵ 9² + 2² + 6² = 11² Input: 9539 Output: 1 ∵ 9² + 5² + 3² + 9² = 14² Input: 12379 Output: 1 ∵ 1² + 2² + 3² + 7² + 9² = 12²
Any content of this website which has been created by Peter Campbell Smith is in the public domain