17
\$\begingroup\$

Let \$n=42\$ (Input)

Then divisors are : 1, 2, 3, 6, 7, 14, 21, 42

Squaring each divisor : 1, 4, 9, 36, 49, 196, 441, 1764

Taking sum (adding) : 2500

Since \$50\times 50=2500\$ therefore we return a truthy value. If it is not a perfect square, return a falsy value.

Examples :

42  ---> true
1   ---> true
246 ---> true
10  ---> false
16  ---> false

This is so shortest code in bytes for each language wins

Thanks to @Arnauld for pointing out the sequence : A046655

\$\endgroup\$
  • 2
    \$\begingroup\$ Can the program output 0 if the result is true, and any other number if the result is false? \$\endgroup\$ – JosiahRyanW Sep 11 '18 at 0:25

39 Answers 39

6
\$\begingroup\$

R, 39 37 bytes

!sum((y=1:(x=scan()))[!x%%y]^2)^.5%%1

Try it online!

Uses the classic "test if perfect square" approach, taking the non-integral part of the square root S^.5%%1 and taking the logical negation of it, as it maps zero (perfect square) to TRUE and nonzero to FALSE.

Thanks to Robert S for saving a couple of bytes!

\$\endgroup\$
  • 1
    \$\begingroup\$ Could you use scan() to save a few bytes? \$\endgroup\$ – Robert S. Sep 10 '18 at 18:31
  • 3
    \$\begingroup\$ @RobertS. doh! I've been doing too much "real" R coding lately! \$\endgroup\$ – Giuseppe Sep 10 '18 at 18:33
6
\$\begingroup\$

JavaScript (ES7),  46 44  42 bytes

Saved 1 byte thanks to @Hedi

n=>!((g=d=>d&&d*d*!(n%d)+g(d-1))(n)**.5%1)

Try it online!

Commented

n =>             // n = input
  !(             // we will eventually convert the result to a Boolean
    (g = d =>    // g is a recursive function taking the current divisor d
      d &&       //   if d is equal to 0, stop recursion 
      d * d      //   otherwise, compute d²
      * !(n % d) //   add it to the result if d is a divisor of n
      + g(d - 1) //   add the result of a recursive call with the next divisor
    )(n)         // initial call to g with d = n
    ** .5 % 1    // test whether the output of g is a perfect square
  )              // return true if it is or false otherwise
\$\endgroup\$
  • 1
    \$\begingroup\$ You can save one byte with d going from n to 0 instead of 2 to n like this: n=>!((g=d=>d?d*d*!(n%d)+g(d-1):0)(n)**.5%1) \$\endgroup\$ – Hedi Sep 11 '18 at 22:17
5
\$\begingroup\$

05AB1E, 5 bytes

ÑnOŲ

Try it online!

How?

ÑnOŲ
Ñ     - divisors
 n    - square
  O   - sum
   Ų - is square?
\$\endgroup\$
5
\$\begingroup\$

Shakespeare Programming Language, 434 428 415 bytes

,.Ajax,.Ford,.Puck,.Act I:.Scene I:.[Enter Ajax and Ford]Ford:Listen tothy.Scene V:.Ajax:You be the sum ofyou a cat.Ford:Is the remainder of the quotient betweenyou I worse a cat?[Exit Ajax][Enter Puck]Ford:If soyou be the sum ofyou the square ofI.[Exit Puck][Enter Ajax]Ford:Be you nicer I?If solet usScene V.[Exit Ford][Enter Puck]Puck:Is the square ofthe square root ofI worse I?You zero.If notyou cat.Open heart

Try it online!

-13 bytes thanks to Jo King!

Outputs 1 for true result, outputs 0 for false result.

\$\endgroup\$
  • \$\begingroup\$ 415 bytes with a third character \$\endgroup\$ – Jo King Sep 11 '18 at 1:39
4
\$\begingroup\$

Python 2, 55 bytes

lambda n:sum(i*i*(n%i<1)for i in range(1,n+1))**.5%1==0

Try it online!

\$\endgroup\$
3
\$\begingroup\$

C (gcc), 67 63 60 59 bytes

-1 bytes thanks to @JonathanFrech

i,s;f(n){for(s=i=0;i++<n;)s+=n%i?0:i*i;n=sqrt(s);n=n*n==s;}

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ Can ++i<=n be i++<n? \$\endgroup\$ – Jonathan Frech Sep 10 '18 at 22:01
  • \$\begingroup\$ @JonathanFrech that seems to work, thanks. \$\endgroup\$ – cleblanc Sep 11 '18 at 13:36
3
\$\begingroup\$

Brachylog, 12 8 bytes

f^₂ᵐ+~^₂

-4 bytes thanks to Fatelize cause i didn't realize brachylog has a factors functions

explanation

f^₂ᵐ+~^₂            #   full code
f                   #       get divisors
 ^₂ᵐ                #           square each one
    +               #       added together
      ~^₂           #       is the result of squaring a number

Try it online!

\$\endgroup\$
  • \$\begingroup\$ f^₂ᵐ is 4 bytes shorter than ḋ{⊇×^₂}ᵘ \$\endgroup\$ – Fatalize Sep 12 '18 at 7:14
3
\$\begingroup\$

MathGolf, 5 4 bytes

─²Σ°

Try it online!

Explanation

─     Get all divisors as list (implicit input)
 ²    Square (implicit map)
  Σ   Sum
   °  Is perfect square?

Very similar to other answers, compared to 05AB1E I gain one byte for my "is perfect square" operator.

\$\endgroup\$
  • \$\begingroup\$ You know, something called "MathGolf" really should have a norm operator... that would have gotten you down to 3 bytes :) \$\endgroup\$ – Misha Lavrov Oct 6 '18 at 16:26
  • \$\begingroup\$ @MishaLavrov that's not a bad idea! Right now I don't have as many vector operations as I'd like, one of these days I'll change that \$\endgroup\$ – maxb Oct 6 '18 at 19:55
3
\$\begingroup\$

MATL, 9 bytes

Z\UsX^tk=

Try it online!

As simple as it gets

Z\ % Divisors of (implicit) input
U  % Square
s  % Sum
X^ % Square root
t  % Duplicate this value
k= % Is it equal to its rounded value?
\$\endgroup\$
2
\$\begingroup\$

Neim, 5 bytes

𝐅ᛦ𝐬q𝕚

Explanation:

𝐅      Factors
 ᛦ      Squared
  𝐬     Summed
    𝕚   is in?
   q    infinite list of square numbers

Try it online!

\$\endgroup\$
2
\$\begingroup\$

PowerShell, 68 56 bytes

param($n)1..$n|%{$a+=$_*$_*!($n%$_)};1..$a|?{$_*$_-eq$a}

Try it online!

Seems long ...
-12 bytes thanks to mazzy

Does exactly what it says on the tin. Takes the range from 1 to input $n and multiplies out the square $_*$_ times whether it's a divisor or not !($n%$_). This makes divisors equal to a nonzero number and non-divisors equal to zero. We then take the sum of them with our accumulator $a. Next, we loop again from 1 up to $a and pull out those numbers where |?{...} it squared is -equal to $a. That is left on the pipeline and output is implicit.

Outputs a positive integer for truthy, and nothing for falsey.

\$\endgroup\$
  • \$\begingroup\$ the rare case where $args[0] is shorter :) 1..$args[0]|%{$a+=$_*$_*!($n%$_)};1..$a|?{$_*$_-eq$a} \$\endgroup\$ – mazzy Sep 10 '18 at 19:00
  • 1
    \$\begingroup\$ @mazzy It's not, because you need $n inside the loop for !($n%$_). But, your rewrite of the sum saved 12 bytes, so thanks! \$\endgroup\$ – AdmBorkBork Sep 10 '18 at 19:11
  • \$\begingroup\$ what a shame. so I would like to find a case where $args[0] is shorter :) \$\endgroup\$ – mazzy Sep 10 '18 at 19:18
2
\$\begingroup\$

Japt, 11 9 7 bytes

-2 bytes from @Giuseppe and another -2 from @Shaggy

â x²¬v1

â x²¬v1             Full program. Implicity input U
â                   get all integer divisors of U
  x²                square each element and sum
    ¬               square root result
     v1           return true if divisible by 1

Try it online!

\$\endgroup\$
2
\$\begingroup\$

APL (Dyalog Unicode), 18 bytes

0=1|.5*⍨2+.*⍨∘∪⍳∨⊢

Try it online!

Anonymous lambda. Returns 1 for truthy and 0 for falsy (test cases in TIO are prettified).

Shoutouts to @H.PWiz for 4 bytes!

How:

0=1|.5*⍨2+.*⍨∘∪⍳∨⊢   ⍝ Main function, argument ⍵ → 42
                ∨⊢   ⍝ Greatest common divisor (∨) between ⍵ (⊢)
               ⍳      ⍝ and the range (⍳) [1..⍵]
              ∪      ⍝ Get the unique items (all the divisors of 42; 1 2 3 6 7 14 21 42)
             ∘        ⍝ Then
            ⍨         ⍝ Swap arguments of
        2+.*          ⍝ dot product (.) of sum (+) and power (*) between the list and 2 
                      ⍝ (sums the result of each element in the vector squared)
       ⍨              ⍝ Use the result vector as base
    .5*               ⍝ Take the square root
  1|                  ⍝ Modulo 1
0=                    ⍝ Equals 0
\$\endgroup\$
  • \$\begingroup\$ Can you do the equivalent of not rather than 0= to save a byte? \$\endgroup\$ – streetster Sep 11 '18 at 6:58
  • \$\begingroup\$ @streetster unfortunately, I cannot for 2 reasons. First, APL's not operator (~), when used monadically, only works with booleans (either 0 or 1). Since any number modulo 1 never equals 1, if I used ~ instead of 0=, I'd get a domain error on any number that's not a perfect square, since decimal values are out of ~'s domain. Furthermore, I cannot simply omit the 0=, since APL's truthy value is 1, not 0, and it wouldn't have a consistent output for falsy values. \$\endgroup\$ – J. Sallé Sep 11 '18 at 12:55
2
\$\begingroup\$

K (oK), 26 25 22 bytes

Solution:

{~1!%+/x*x*~1!x%:1+!x}

Try it online!

Explanation:

{~1!%+/x*x*~1!x%:1+!x} / the solution
{                    } / lambda taking x as input
                   !x  / range 0..x-1                        \
                 1+    / add 1                               |
              x%:      / x divided by and save result into x |
            1!         / modulo 1                            | get divisors
           ~           / not                                 |
         x*            / multiply by x                       /
       x*              / multiply by x (aka square)          > square
     +/                / sum up                              > sum up
    %                  / square root                         \  
  1!                   / modulo 1                            | check if a square
 ~                     / not                                 / 

Notes:

  • -1 bytes taking inspiration from the PowerShell solution
  • -3 bytes taking inspiration from the APL solution
\$\endgroup\$
2
\$\begingroup\$

Pari/GP, 23 bytes

n->issquare(sigma(n,2))

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Matlab, 39 37 bytes

@(v)~mod(sqrt(sum(divisors(v).^2)),1)

Unfortunately, it doesn't work on Octave (on tio) so no tio link.

Note As @LuisMendo stated, divisors() belongs to Symbolic Toolbox.

\$\endgroup\$
  • 1
    \$\begingroup\$ It looks like divisors belongs to the Symbolic Toolbox. You should state that in the title. Also, you can use ~··· instead of ···==0 \$\endgroup\$ – Luis Mendo Sep 10 '18 at 21:39
  • \$\begingroup\$ You can shorten this by using sum(...)^.5 instead of sqrt(sum(...)) \$\endgroup\$ – Sanchises Dec 11 '18 at 14:56
2
\$\begingroup\$

Haskell, 78 64 53 bytes

-14 bytes thanks to Ørjan Johansen. -11 bytes thanks to ovs.

f x=sum[i^2|i<-[1..x],x`mod`i<1]`elem`map(^2)[1..x^2]

Try it online!

Hey, it's been a while since I've... written any code, so my Haskell and golfing might a bit rusty. I forgot the troublesome Haskell numeric types. :P

\$\endgroup\$
  • 1
    \$\begingroup\$ It's shorter (but slower) to avoid those conversions by searching for the square root with another list comprehension. Try it online! \$\endgroup\$ – Ørjan Johansen Sep 11 '18 at 2:36
  • 1
    \$\begingroup\$ Shorter: f x|s<-sum[i^2|i<-[1..x],mod x i<1]=round(sqrt$toEnum s)^2==s \$\endgroup\$ – Damien Sep 11 '18 at 9:22
  • 2
    \$\begingroup\$ Building up on Ørjan Johansen's suggestion, this should work for 53 bytes. \$\endgroup\$ – ovs Sep 11 '18 at 13:16
2
\$\begingroup\$

Pyt, 7 bytes

ð²ƩĐř²∈

Try it online!

Explanation

            Implicit input
ð           Get list of divisors
 ²          Square each element
  Ʃ         Sum the list [n]
   Đ        Duplicate the top of the stack
    ř²      Push the first n square numbers
      ∈     Is n in the list of square numbers?
            Implicit output

ð²Ʃ√ĐƖ=

Try it online!

Explanation

            Implicit input
ð           Get list of divisors
 ²          Square each element
  Ʃ         Sum the list [n]
   √        Take the square root of n
    Đ       Duplicate the top of the stack
     Ɩ      Cast to an integer
      =     Are the top two elements on the stack equal to each other?
            Implicit output

ð²Ʃ√1%¬

Try it online!

Explanation

            Implicit input
ð           Get list of divisors
 ²          Square each element
  Ʃ         Sum the list [n]
   √        Take the square root of n
    1%      Take the square root of n modulo 1
      ¬     Negate [python typecasting ftw :)]
            Implicit output
\$\endgroup\$
1
\$\begingroup\$

Husk, 6 bytes

£İ□ṁ□Ḋ

Try it online!

Explanation

£İ□ṁ□Ḋ  -- example input 12
     Ḋ  -- divisors: [1,2,3,4,6,12]
   ṁ    -- map the following ..
    □   -- | square: [1,4,9,16,36,144]
        -- .. and sum: 210
£       -- is it element of (assumes sorted)
 İ□     -- | list of squares: [1,4,9,16..196,225,..
\$\endgroup\$
1
\$\begingroup\$

Proton, 41 bytes

a=>sum(q*q for q:1..a+1if a%q<1)**.5%1==0

Try it online!

Similar approach to the Python answer.

\$\endgroup\$
1
\$\begingroup\$

Mathematica, 32 bytes

IntegerQ@Sqrt[2~DivisorSigma~#]&

Pure function. Takes a number as input and returns True or False as output. Not entirely sure if there's a shorter method for checking perfect squares.

\$\endgroup\$
1
\$\begingroup\$

Octave / MATLAB, 43 bytes

@(n)~mod(sqrt(sum(find(~mod(n,1:n)).^2)),1)

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Red, 67 bytes

func[n][s: 0 repeat d n[if n % d = 0[s: d * d + s]](sqrt s)% 1 = 0]

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Scala, 68 67 bytes

def j(s:Int)=Math.sqrt((1 to s).filter(s%_<1).map(a=>a*a).sum)%1==0

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Perl 6, 34 bytes

-1 byte thanks to nwellnhof

{grep($_%%*,1..$_)>>².sum**.5%%1}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ **.5 is one byte shorter than .sqrt. \$\endgroup\$ – nwellnhof Sep 11 '18 at 14:42
1
\$\begingroup\$

F#, 111 bytes

let d n=Seq.where(fun v->n%v=0){1..n}
let u n=
 let m=d n|>Seq.sumBy(fun x->x*x)
 d m|>Seq.exists(fun x->x*x=m)

Try it online!

So d gets the divisors for all numbers between 1 and n inclusive. In the main function u, the first line assigns the sum of all squared divisors to m. The second line gets the divisors for m and determines if any of them squared equals m.

\$\endgroup\$
1
\$\begingroup\$

Perl 5, 47 bytes

$a+=$_*$_*!($n%$_)for 1..$n;$a=!($a**.5=~/\D/); 

Returns 1 for true and nothing for false.

Explanation:

$a+=              for 1..$n;                      sum over i=1 to n
    $_*$_                                         square each component of the sum
         *!($n%$_)                                multiply by 1 if i divides n.
                            $a=                   a equals
                                ($a**.5           whether the square root of a
                               !       =~/\D/);   does not contain a non-digit.
\$\endgroup\$
1
\$\begingroup\$

Groovy, 47 bytes

A lambda accepting a numeric argument.

n->s=(1..n).sum{i->n%i?0:i*i}
!(s%Math.sqrt(s))

Explanation

(1..n) creates an array of the values 1 to n

n%i is false (as 0 is falsy) if i divides n without remainder

n%i ? 0 : i*i is the sum of the square of the value i if it divides n without remainder, otherwise is 0

sum{ i-> n%i ? 0 : i*i } sums the previous result across all i in the array.

s%Math.sqrt(s) is false (as 0 is falsy) if the sqrt of s divides s without remainder

!(s%Math.sqrt(s)) returns from the lambda (return implicit on last statement) !false when the sqrt of s divides s without remainder

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Java 8, 75 70 bytes

n->{int s=0,i=0;for(;++i<=n;)s+=n%i<1?i*i:0;return Math.sqrt(s)%1==0;}

-5 bytes thanks to @archangel.mjj.

Try it online.

Explanation:

n->{             // Method with integer parameter and boolean return-type
  int s=0,       //  Sum-integer, starting at 0
      i=0;       //  Divisor integer, starting at 0
  for(;++i<=n;)  //  Loop `i` in the range [1, n]
    s+=n%i<1?    //   If `n` is divisible by `i`:
        i*i      //    Increase the sum by the square of `i`
       :         //   Else:
        0;       //    Leave the sum the same by adding 0
  return Math.sqrt(s)%1==0;}
                 //  Return whether the sum `s` is a perfect square
\$\endgroup\$
  • 1
    \$\begingroup\$ Hi, you can cut 5 bytes by removing the t variable (do the eval and assignment within the body of the for loop), like so: n->{int s=0,i=0;for(;++i<=n;)s+=n%i<1?i*i:0;return Math.sqrt(s)%1==0;} \$\endgroup\$ – archangel.mjj Sep 13 '18 at 8:26
  • \$\begingroup\$ @archangel.mjj Ah, of course. Not sure how I missed that. Thanks! :) \$\endgroup\$ – Kevin Cruijssen Sep 13 '18 at 8:36
1
\$\begingroup\$

Wolfram Language (Mathematica), 24 20 bytes

1∣Norm@Divisors@#&

Try it online!

Divisors finds all the divisors of a number, Norm takes the square root of the sum of squares, and then we test if this is divisible by 1 (i.e., is an integer).

\$\endgroup\$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.