23
\$\begingroup\$

A powerful number is a positive integer \$n\$ such that for every prime \$p\$ that divides \$n\$, \$p^2\$ also divides \$n\$. Or equivalently, \$n\$ is powerful if and only if it can be written in the form \$n = a^2b^3\$, where \$a\$ and \$b\$ are positive integers.

For example, \$972 = 2^2 \times 3^5\$ is powerful, because \$2^2\$ and \$3^2\$ both divide \$972\$. And we have \$972 = 6^2 \times 3^3\$.

\$961 = 31^2\$ is also powerful, because \$31^2\$ divides \$961\$. And we have \$961 = 31^2 \times 1^3\$.

On the other hand, \$1001 = 7 \times 11 \times 13\$ is not powerful, because \$7^2\$ does not divide \$1001\$. It is not possible to write \$1001\$ in the form \$a^2b^3\$.

Here is a list of all the powerful numbers less than 1000:

1, 4, 8, 9, 16, 25, 27, 32, 36, 49, 64, 72, 81, 100, 108, 121, 125, 128, 144, 169, 196, 200, 216, 225, 243, 256, 288, 289, 324, 343, 361, 392, 400, 432, 441, 484, 500, 512, 529, 576, 625, 648, 675, 676, 729, 784, 800, 841, 864, 900, 961, 968, 972

This is sequence A001694 in the OEIS.

Task

Given a positive integer \$n\$, determine whether or not it is a powerful number.

This is , so the shortest code in bytes wins.

This is also a so you may use your language's convention for truthy/falsy (swapping truthy and falsy is allowed), or use two distinct, fixed values to represent true or false.

\$\endgroup\$
4
  • \$\begingroup\$ Related \$\endgroup\$
    – alephalpha
    Jul 28, 2023 at 5:31
  • 4
    \$\begingroup\$ The intuition bridging the two definitions is that for every prime factor that occurs a nonzero number of times to occur at least two times, it has to still "come with" a square. This invites a third formulation where powerful numbers are those of the form a²b where b divides a. dingledooper seems to have already leveraged this, but slightly different angles may be shorter in different languages. \$\endgroup\$ Jul 28, 2023 at 7:30
  • 4
    \$\begingroup\$ These are the numbers such that \$\text{rad}(n)^2 | n\$, where \$\text{rad}\$ is the product of unique prime factors. \$\endgroup\$ Jul 28, 2023 at 14:36
  • \$\begingroup\$ @pajonk: okay, got it, thanks \$\endgroup\$ Jul 29, 2023 at 12:34

31 Answers 31

9
\$\begingroup\$

Python 3, 43 bytes

Returns False for a powerful number, and True otherwise.

f=lambda n,i=1:i>n or(n/i)**.5%i>0<f(n,i+1)

Try it online!

Checks the condition that n is in the form a^2*b^3 by asserting that n/a^3 is a perfect square. In Python this would look something like (n/a**3)**.5%1==0. This condition can be rearranged so that it is slightly golfier:

(n/a**3)**.5%1==0
n**.5/a**1.5%1==0
n**.5/a**.5/a%1==0
(n/a)**.5/a%1==0
(n/a)**.5%a==0
\$\endgroup\$
7
\$\begingroup\$

Jelly, 4 bytes

ÆE1e

Try it online!

Inverted native truthy/falsy semantics: 0 for powerful numbers, 1 otherwise.

  1e    Is 1 an element of
ÆE      the array of the input's prime exponents?
\$\endgroup\$
6
\$\begingroup\$

R, 24 bytes

\(n)all((n/1:n)^.5%%1:n)

Attempt This Online!

Port of @dingledooper's approach.


R, 26 bytes

\(n,i=1:n)n%in%(i^2%o%i^3)

Attempt This Online!

Uses the alternative characterization from the question.

\$\endgroup\$
6
\$\begingroup\$

Python, 43 bytes

f=lambda n,c=1:f(n,c+1)if c**n%n else n/c%c

Try it online!

Outputs Truthy/Falsey reversed. A different method than dingledooper's solution, without using square roots.

The idea is to find the square-free part c of n, that is, the product of the distinct prime factors of n. We do this by counting up to the smallest c where c**n%n is 0, which checks that the prime factors of c, if copied many times, cover those of n.

Having found c, we check whether n/c%c is zero, which is equivalent to n being divisible by c**2. This confirms that n includes each of its prime factors at least twice. This also works in Python 2 where / is integer division rather than float division, since n is divisible by c, for a solution with only exact integer arithmetic.

Rather than finding the smallest c with c**n%n, we could instead check all values of c from 1 to n for one where c**n%n and n/c%c are both 0. This could look like:

44 bytes

f=lambda n,c=1:c>n or(c**n%n+n/c%c)*f(n,c+1)

Try it online!

39 bytes with exit code

def f(n,c=1):c**n%n+n/c%c>0!=f(n,-~c%n)

Try it online!

From @loopy walt

Python 2, 42 bytes

d=n=input()
while n%d**2:d-=1
print d**n%n

Try it online!

Finds the largest value d where n is divisible by d**2, then checks that it includes each distinct prime factor of n via d**n%n being zero.

\$\endgroup\$
1
  • \$\begingroup\$ If you allow yourself to signal by exit code you can save a few bytes, e.g. -5 off your 44 byter. \$\endgroup\$
    – loopy walt
    Jul 30, 2023 at 14:09
5
\$\begingroup\$

TI-BASIC (TI-84 Plus/Plus CE), 35 27 Bytes

-8 bytes thanks to Bbrk24

Prompt A:For(B,1,A:If not(fPart(√(A/B:Stop:End:Disp 0

The thing right after A/B is a cube (3). The thing right before the A/B is a sqrt symbol.

Does nothing and terminates if your number is powerful and prints 0 and terminates if your number is not powerful.

Ungolfed

Prompt A
For(B,1,A
If not(fPart(√(A/B
Stop
End
Disp 0

Explained

Prompt A              Asks user for input A
For(B,1,A             For loop: increase B by 1 from 1 until it reaches A
If                    If...
            √(        square root of...
              A/B    A/B^3...
  not(fPart(          is a whole number...
Stop                  then stop execution.
End                   End of while loop, go back to While A>B
Disp 0                If, eventually, B does exceed A, then A is not a powerful number.

TI-BASIC programs are scored by tokens bytes, not characters.
TI-BASIC also completes parentheses for you.

Edit: Test cases

Truthy:
123

Falsy:
456

\$\endgroup\$
7
  • \$\begingroup\$  is a private-use character. Why not use ³ (U+00B3 SUPERSCRIPT THREE)? \$\endgroup\$
    – Bbrk24
    Jul 31, 2023 at 12:53
  • \$\begingroup\$ Also, I think you can save around six bytes by using For(B,0,A instead of 0→B:While A>B:B+1→B. I don't have my calculator on me so I can't test it, and I'm not sure off the top of my head whether For( and While are 1- or 2-byte tokens. \$\endgroup\$
    – Bbrk24
    Jul 31, 2023 at 12:58
  • \$\begingroup\$ @Bbrk24 it was actually For(B,1,A to avoid dividing by zero but thanks! for some reason it saved 8 bytes on my calc. \$\endgroup\$ Jul 31, 2023 at 14:42
  • 1
    \$\begingroup\$ You should be able to remove the Disp, and the 0 will be printed instead of Done \$\endgroup\$
    – MarcMush
    Aug 11, 2023 at 8:13
  • 1
    \$\begingroup\$ Taking input as Ans also saves a few bytes \$\endgroup\$
    – MarcMush
    Aug 11, 2023 at 8:20
4
\$\begingroup\$

Excel, 42 bytes

=LET(a,SEQUENCE(A1),OR(a^2*TOROW(a^3)=A1))

Input in cell A1.

\$\endgroup\$
4
\$\begingroup\$

J, 12 10 8 bytes

1 e._&q:

Try it online!

-2 by using Unrelated String's approach of checking for 1 instead of verifying that every exponents was 2 or more

-2 thanks to Bubbler for a shorter way to get prime exponents

  • _&q: shows the number's prime exponents
  • 1 e. checks if all exponents are greater than 1, by checking if 1 is an element and using 0 for truthy and 1 for falsy
\$\endgroup\$
2
  • 2
    \$\begingroup\$ You can replace 1{2&p: with _&q:. \$\endgroup\$
    – Bubbler
    Jul 28, 2023 at 6:35
  • \$\begingroup\$ Funnily enough, the only reason I thought of checking for 1 is Jelly's ÆE includes zeroes \$\endgroup\$ Jul 28, 2023 at 7:09
4
\$\begingroup\$

K (ngn/k), 18 bytes

{|/~1!%x%/3#,1+!x}

Try it online!

Works more like dingledooper's Python solution.

{|/~1!%x%/3#,1+!x}
             1+!x   1..x
       x%/3#,       starting from x, divide by above three times
      %             square root of each
 |/~1!              test if any of them has zero fractional part

K (ngn/k), 22 bytes

{|//x=*/:/1_*\3#,1+!x}

Try it online!

A bit of a convoluted way to check if the given number x is a^2 * b^3. Returns 1 if x is a powerful number, 0 otherwise.

{|//x=*/:/1_*\3#,1+!x}
                 1+!x   1..x inclusive -> A
              3#,       an array that contains three copies of A
            *\     cumulative product (A; A^2; A^3)
          1_       drop first
      */:/    reduce by cartesian product by multiplication
    x=        boolean matrix indicating each number is equal to input
 |//          max of all booleans
\$\endgroup\$
4
\$\begingroup\$

Dyalog APL, 21 bytes

⊢(⊣|*⍨)0⌈/∘⍸⍤=⊢|⍨2*⍨⍳

port of xnor's Python answer. Outputs inverse truthy value

⊢(⊣|*⍨)0⌈/∘⍸⍤=⊢|⍨2*⍨⍳ ⍝ implicit n
                    ⍳ ⍝ list values 1..n
                 2*⍨ ⍝ square each value
              ⊢|⍨    ⍝ mod by n
        0   =        ⍝ find where index is 0
         ⌈/∘⍸⍤        ⍝ Get max index divisible (d)
⊢(⊣|*⍨)              ⍝ then check d^n mod n
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$ Jul 29, 2023 at 16:18
4
\$\begingroup\$

C, 69 63 bytes

-6 bytes thanks to @c-- suggesting to reverse the loops and pointing out that I'd managed to leave in an unused variable.

i,j;f(n){for(i=n;i;i--)for(j=n;j;j--)n*=i*i*j*j*j!=n;return!n;}

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ return!n -> n=!n \$\endgroup\$ Jul 30, 2023 at 15:13
  • \$\begingroup\$ @landfillbaby I wanted the submission to be compatible with any compiler :) \$\endgroup\$
    – Peter
    Jul 30, 2023 at 16:38
  • 1
    \$\begingroup\$ Thanks, @c-- :) \$\endgroup\$
    – Peter
    Aug 4, 2023 at 17:22
3
\$\begingroup\$

Factor + math.primes.factors math.unicode, 30 29 bytes

[ group-factors unzip 1 ∋ ]

Try it online!

Port of Unrelated String's Jelly answer.

-1 by using unzip instead of values to get at the exponents

  • group-factors get an associative array of a number's prime factors and exponents
  • unzip get just the exponents
  • 1 ∋ is 1 in this?
\$\endgroup\$
3
\$\begingroup\$

Octave, 22 bytes

@(n)n-(t=1:n).^2'*t.^3
  • The output for powerful input is a matrix containing at least one entry equal to 0, which is falsy in Octave.
  • The output for a non-powerful input is a non-empty matrix with all entries different than zero, which is truthy.

Try it online! The footer code contains truthiness/falsihood test.

Or verify all test cases. The footer code displays the input number if powerful (falsy output), or -- otherwise (truthy output).

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

Vyxal, 4 bytes

ǏΠ²Ḋ

Try it Online!

Uses Command Master's insight that these are numbers where the product of the distinct prime factors of the input is divisible by the input.

ǏΠ²Ḋ  # implicit input of integer
Ǐ     # distinct prime factors
 Π    # the product of this list
  ²   # squared
   Ḋ  # is divisible by the (implicit) input
\$\endgroup\$
2
3
\$\begingroup\$

Nekomata + -e, 3 bytes

ƒ1>

Attempt This Online!

ƒ1>
ƒ       Factor
 1>     Check if all exponents are greater than 1
\$\endgroup\$
2
\$\begingroup\$

05AB1E, 3 bytes

Ó1å

Outputs an inverted 05AB1E boolean: \$1\$ if it's NOT a powerful numbers; \$0\$ if it is a powerful number (only 1 is truthy in 05AB1E).

Port of @UnrelatedString's Jelly answer, so make sure to upvote that answer as well!

Try it online or verify all test cases.

Explanation:

Ó    # Get a list of exponents of the (implicit) input's prime factorization
 1å  # Does this list contain a 1?
     # (after which the result is output implicitly)
\$\endgroup\$
2
\$\begingroup\$

Arturo,  33  30 bytes

$=>[in? 1tally factors.prime&]

Try it!

Port of Unrelated String's Jelly answer.

$=>[               ; a function where input is assigned to &
    in? 1          ; is 1 in
    tally          ; counts of
    factors.prime& ; input's prime factors
]                  ; end function
\$\endgroup\$
2
\$\begingroup\$

Racket, 101 bytes

(define(f n)((λ(D ?)(=(count(λ(p)(and(? p n)(?(sqr p)n)))D)(length D)))(prime-divisors n)divides?))

Try it online!


Explanation

We create a function f that takes one input n. We find the list of prime divisors of n and call it D. We then iterate through the list and check whether n is divisable by each element and n is divisable by each element squared. If both conditions are satisfied, we increment a counter. After iterating through list, we retrieve the total count and test whether the count is the same as the length of the list of divisors. If it is, then the number is a Powerful Number.

The ungolfed version is simpler to understand:

(define (f n)
  (let ([D (prime-divisors n)])
    (= (count (lambda (p)
                (and (divides? p n)
                     (divides? (sqr p) n)))
              D)
       (length D))))

Have a wonderful weekend ahead!

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

Japt, 7 bytes

k e@vX²

Try it here

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

JavaScript, 32 bytes

A port of xnor's solution to JavaScript:

f=(n,c=1)=>c**n%n?f(n,c+1):n/c%c
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Welcome to Code Golf, and nice first answer! \$\endgroup\$
    – The Thonnu
    Jul 29, 2023 at 13:54
  • 1
    \$\begingroup\$ Thanks you man. \$\endgroup\$
    – Akif9748
    Jul 29, 2023 at 15:43
  • \$\begingroup\$ By the way, you could add a link to an online interpreter like Try it online so other people can verify your code. \$\endgroup\$
    – The Thonnu
    Jul 29, 2023 at 16:07
2
\$\begingroup\$

Thunno 2 G, 2 bytes

ḟḅ

Try it online! or verify the first few powerful numbers

Port of Unrelated String's Jelly answer. Output with inverted booleans. Add the ! flag to take the logical NOT.

Explanation

    # Implicit input
ḟ   # Get the list of prime factor exponents
 ḅ  # Check for each if it equals one
    # Take the maximum of this list
    # Implicit output
\$\endgroup\$
2
\$\begingroup\$

Brachylog, 8 bytes

Ċ^₂ʰ^₃ᵗ×

Try it online!

Takes input as the Output variable. Outputs true. or false. as you would expect.

Explanation

It’s just a description of the alternative definition.

Ċ          Take a couple of 2 variables
 ^₂ʰ       Square the first one
    ^₃ᵗ    Cube the last one
       ×   Multiply them: it must be equal to the given input
           Brachylog will implicitly check if such a couple of variables Ċ exists
\$\endgroup\$
2
\$\begingroup\$

Ruby -rprime, 32 bytes

Prime.prime_division returns a number's prime factors \$\prod_{k=1}^\infty {p_k}^{e_k}\$ in the form [ [p1, e1], [p2, e2], ... ] so this function checks whether every exponent is 2 or more.

->n{n.prime_division.all?{_2>1}}

Attempt This Online!

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

APL(NARS), 8 chars

1∊≢¨⊂⍨π⎕

It return 0 if the number is as question ask, 1 otherwise. It is read in reverse ⎕π⍨⊂¨≢∊1 Call for input,π return the list of factors of input, ⍨⊂ doing partition as inputinput,¨≢ for each element list, of partition return the lenght,∊1 see if in the last list there is 1

test:

      1∊≢¨⊂⍨π⎕
⎕:
      36
0
~
      a/⍨∼{1∊≢¨⊂⍨π⍵}¨a←⍳100
┌14─────────────────────────────────────┐
│ 1 4 8 9 16 25 27 32 36 49 64 72 81 100│
└~──────────────────────────────────────┘
\$\endgroup\$
2
\$\begingroup\$

Mathematica, 40 39 38 36 27 bytes

FactorInteger@#1∨#==1&

The first is \[VectorGreater], the second is \[Or\]. Assuming UTF-8 encoding, they both occupy 3 bytes.

Try this online!

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

Regex (ECMAScript or better), 50 bytes

^((?=(xx+?)\2+$)((?=\2+$)(?=(x+)(\4+$))\5){2,})*x$

Try it online! - ECMAScript
Try it online! - Perl
Try it online! - Java
Try it online! - Python
Try it online! - Ruby
Try it online! - PCRE
Try it online! - .NET

I adapted this on 2018-12-26, as a slight modification to the regex that matches numbers of the form \$n^k\$, where \$k\$ is a constant. In its implementation, that regex actually matches numbers that are either \$0\$ or of the form \$n^k=\prod_{i=0}^{q} p_i^{k_i}=p_0^{k_0}p_1^{k_1}p_2^{k_2}...p_q^{k_q}\$ where all \$p_m\$ are distinct primes, all \$k_m=k\$, and \$q\ge 0\$.

The only changes here, to match powerful numbers instead, are to make \$k_m\ge 2\$ (which takes 1 extra byte), and not to match \$0\$ (which saves 1 byte).

In other words, this regex works by dividing away each prime factor, from smallest to largest, asserting along the way that each distinct prime is divided away at least twice, with an end result of \$1\$.

^                     # N = input number (initial value of tail)
(                     # Loop/iterate the following:
    (?=(xx+?)\2+$)        # \2 = smallest prime factor of tail
    (                     # Loop/iterate the following:
        (?=\2+$)              # Assert tail is still divisible by \2
        (?=(x+)(\4+$))        # \4 = largest proper divisor of tail
                                   = tail / \2 (implicitly);
                              # \5 = tail - \4 (a tool to make tail = \4)
        \5                    # tail -= \5, i.e. tail = \4
    ){2,}                 # Iterate the above at least 2 times
)*                    # Iterate the above any number of times, minimum 0
x$                    # Assert tail == 1

Retina 0.8.2, 56 bytes

.+
$*
^((?=(11+?)\2+$)((?=\2+$)(?=(1+)(\4+$))\5){2,})*1$

Try it online!

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

Retina 0.8.2, 64 bytes

.+
$*
^((.){2,})(?<!^\3+(..+))\1*$(?<!^\4*(?(2)$)(((?<-2>)\1)+))

Try it online! Link includes test cases. Outputs 0 for a powerful number, 1 if not. Explanation:

.+
$*

Convert to unary.

^((.){2,})

Search for a nontrival integer...

(?<!^\3+(..+))

... that is not composite...

\1*$

... and is a factor of the input...

(?<!^\4*(?(2)$)(((?<-2>)\1)+))

... and whose square is not a factor of the input.

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

Charcoal, 25 bytes

Nθ⊙…·²θ∧∧¬﹪θι﹪θ×ιι⬤…²ι﹪ιλ

Try it online! Link is to verbose version of code. Outputs an inverted Charcoal boolean, i.e. - if the input is not a powerful number, nothing if it is. Explanation:

Nθ                          Input as an integer
   …·                       Inclusive range from
     ²                      Literal integer `2` to
      θ                     Input integer
  ⊙                         Any value satisfies
           θ                Input integer
         ¬﹪                 Is divisible by
            ι               Current value
        ∧                   Logical And
              θ             Input integer
             ﹪              Is not divisible by
               ×ιι          Current value squared
       ∧                    Logical And
                   …        Range from
                    ²       Literal integer `2` to
                     ι      Current value
                  ⬤         All satisfy
                       ι    Outer value
                      ﹪     Is not divisible by
                        λ   Inner value
                            Implicitly print
\$\endgroup\$
1
\$\begingroup\$

Desmos, 47 bytes

f(k)=0^{∏_{n=1}^{k^{.5}}mod((k/n^2)^{1/3},1)}

In case it bothers anyone, k/n^2 can't be shortened to k/nn because k/nn is parsed as k/n * n when we actually want k/(n*n).

Try It On Desmos!

Try It On Desmos! - Prettified

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

Perl 5 -ap, 43 bytes

//&map$\+=$_**2*$'**3=="@F",@;for@;=1..$_}{

Try it online!

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

Vyxal g, 23 bitsv2, 2.875 bytes

∆Ǐċ

Try it Online!

Bitstring:

00010101110001100111100

Prime exponents, check if not equal to one, minimum of that list (will always be greater than one for a powerful number)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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