39
\$\begingroup\$

A simple but hopefully not quite trivial challenge:

Write a program or function that adds up the kth powers dividing a number n. More specifically:

  • Input: two positive integers n and k (or an ordered pair of integers, etc.)
  • Output: the sum of all of the positive divisors of n that are kth powers of integers

For example, 11! = 39916800 has six divisors that are cubes, namely 1, 8, 27, 64, 216, and 1728. Therefore given inputs 39916800 and 3, the program should return their sum, 2044.

Other test cases:

{40320, 1} -> 159120
{40320, 2} -> 850
{40320, 3} -> 73
{40320, 4} -> 17
{40320, 5} -> 33
{40320, 6} -> 65
{40320, 7} -> 129
{40320, 8} -> 1
{46656, 1} -> 138811
{46656, 2} -> 69700
{46656, 3} -> 55261
{46656, 4} -> 1394
{46656, 5} -> 8052
{46656, 6} -> 47450
{46656, 7} -> 1
{1, [any positive integer]} -> 1

This is code golf, so the shorter your code, the better. I welcome golfed code in all kinds of different languages, even if some other language can get away with fewer bytes than yours.

\$\endgroup\$
2
  • 14
    \$\begingroup\$ When I first saw your challenge, I had the weird feeling that it was a Metallica song title. \$\endgroup\$
    – Arnauld
    Feb 10, 2017 at 14:54
  • 3
    \$\begingroup\$ What? There's no Mathematica built-in for this? \$\endgroup\$
    – boboquack
    Feb 10, 2017 at 22:47

26 Answers 26

13
\$\begingroup\$

05AB1E, 9 bytes

DLImDŠÖÏO

Try it online!

Explanation

Example input 46656, 3

D          # duplicate first input
           # STACK: 46656, 46656
 L         # range [1 ... first input]
           # STACK: 46656, [1 ... 46656]
  Im       # each to the power of second input
           # STACK: 46656, [1, 8, 27 ...]
    D      # duplicate
           # STACK: 46656, [1, 8, 27 ...], [1, 8, 27 ...]
     Š     # move down 2 spots on the stack
           # STACK: [1, 8, 27 ...], 46656, [1, 8, 27 ...]
      Ö    # a mod b == 0
           # STACK: [1, 8, 27 ...], [1,1,1,1,0 ...]
       Ï   # keep only items from first list which are true in second
           # STACK: [1, 8, 27, 64, 216, 729, 1728, 5832, 46656]
        O  # sum
           # OUTPUT: 55261
\$\endgroup\$
7
\$\begingroup\$

Mathematica, 28 bytes

Tr[Divisors@#⋂Range@#^#2]&

Unnamed function taking n and k as inputs in that order.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ DivisorSum is frustratingly close to being useful here. \$\endgroup\$
    – user61980
    Feb 10, 2017 at 19:24
6
\$\begingroup\$

Jelly, 7 6 bytes

-1 byte thanks to Dennis (traverse an implicit range)
A clever efficiency save also by Dennis at 0-byte cost
(Previously ÆDf*€S would filter keep those divisors that are a power of k of any natural number up to n. But note that n can only ever have a divisor of ik if it has a divisor of i anyway!)

ÆDf*¥S

Try it online!

How?

ÆDf*¥S - Main link: n, k
ÆD     - divisors of n  -> divisors = [1, d1, d2, ..., n]
    ¥  - last two links as a dyadic chain
  f    -     filter divisors keeping those that appear in:
   *   -     exponentiate k with base divisors (vectorises)
       - i.e. [v for v in [1, d1, d2, ..., n] if v in [1^k, d1^k, ..., n^k]]
     S - sum
\$\endgroup\$
0
5
\$\begingroup\$

Haskell, 37 35 34 bytes

n!k=sum[x^k|x<-[1..n],n`mod`x^k<1]

Try it online! Usage:

Prelude> 40320 ! 1
159120

The code is quite inefficient because it always computes 1^k, 2^k, ..., n^k.

Edit: Saved one byte thanks to Zgarb.

Explanation:

n!k=             -- given n and k, the function ! returns
 sum[x^k|        -- the sum of the list of all x^k
   x<-[1..n],    -- where x is drawn from the range 1 to n
   n`mod`x^k<1]  -- and n modulus x^k is less than 1, that is x^k divides n
\$\endgroup\$
1
  • 1
    \$\begingroup\$ mod n(x^k) can be n`mod`x^k. \$\endgroup\$
    – Zgarb
    Feb 10, 2017 at 14:08
5
\$\begingroup\$

Python 2, 54 52 bytes

lambda x,n:sum(i**n*(x%i**n<1)for i in range(1,-~x))

Thanks @Rod for cutting off 2 bytes.

\$\endgroup\$
1
  • \$\begingroup\$ You can replace x%i**n==0 with x%i**n<1, and move to the other side as i**n*(x%i**n<1) \$\endgroup\$
    – Rod
    Feb 10, 2017 at 12:05
4
\$\begingroup\$

Ruby, 45 bytes

->n,m{(1..n).reduce{|a,b|n%(c=b**m)<1?a+c:a}}

Would be shorter using "sum" in Ruby 2.4. Time to upgrade?

\$\endgroup\$
1
  • 4
    \$\begingroup\$ Time to upgrade. \$\endgroup\$
    – Yytsi
    Feb 10, 2017 at 10:34
4
\$\begingroup\$

MATL, 10 bytes

t:i^\~5M*s

Try it online!

How it works

Example with 46656, 6.

t      % Implicitly input n. Duplicate
       % STACK: 46656, 46656
:      % Range
       % STACK: 46656, [1 2 ... 46656]
i      % Input k
       % STACK: 46656, [1 2 ... 46656], 6
^      % Power, element-wise
       % STACK: 46656, [1 64 ... 46656^6]
\      % Modulo
       % STACK: [0 0 0 1600 ...]
~      % Logically negate
       % STACK: [true true true false ...]
5M     % Push second input to function \ again
       % STACK: [true true true false ...], [1^6 2^6 ... 46656^6]
*      % Multiply, element-wise
       % STACK: [1 64 729 0 ...]
s      % Sum of array: 47450
       % Implicitly display
\$\endgroup\$
4
\$\begingroup\$

Perl 6, 39 bytes

->\n,\k{sum grep n%%*,({++$**k}...*>n)}

How it works

->\n,\k{                              }  # A lambda taking two arguments.
                        ++$              # Increment an anonymous counter
                           **k           # and raise it to the power k,
                       {      }...       # generate a list by repeatedly doing that,
                                  *>n    # until we reach a value greater than n.
            grep n%%*,(              )   # Filter factors of n from the list.
        sum                              # Return their sum.

Try it

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

Python 2, 50 bytes

f=lambda n,k,i=1:n/i and(n%i**k<1)*i**k+f(n,k,i+1)

Try it online! Large inputs may exceed the recursion depth depending on your system and implementation.

\$\endgroup\$
1
  • \$\begingroup\$ this is 49 bytes, and it may be valid since True quacks like 1, but it's a strange default imo \$\endgroup\$
    – c--
    Apr 24, 2023 at 15:33
3
\$\begingroup\$

JavaScript (ES7),  56 53  47 bytes

Expects (n)(k).

n=>k=>eval("for(i=t=0;i++<n;)t+=n%i**k?0:i**k")

Try it online!

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

Japt, 10 bytes

Saved lots of bytes thanks to @ETHproductions

òpV f!vU x

Explanation

òpV f!vU x
ò           // Creates a range from 0 to U
 pV         // Raises each item to the power of V (Second input)
    f       // Selects all items Z where
     !vU    //   U is divisible by Z
            //   (fvU would mean Z is divisible by U; ! swaps the arguments)
         x  // Returns the sum of all remaining items

Test it online!

\$\endgroup\$
4
  • \$\begingroup\$ Does vU detect numbers divisible by U, or numbers that divide U? \$\endgroup\$ Feb 10, 2017 at 18:43
  • \$\begingroup\$ @GregMartin fvU filters to items that are divisible by U; f!vU filters to items that U is divisible by. ! swaps the arguments. \$\endgroup\$
    – Oliver
    Feb 10, 2017 at 18:47
  • \$\begingroup\$ Cool, so the code looks right, but the explanation might need to be tweaked. \$\endgroup\$ Feb 10, 2017 at 18:53
  • \$\begingroup\$ @GregMartin Should be clearer now. \$\endgroup\$ Feb 10, 2017 at 18:55
2
\$\begingroup\$

Scala 63 bytes

(n:Int,k:Int)=>1 to n map{Math.pow(_,k).toInt}filter{n%_==0}sum
\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES7), 49 46 bytes

n=>g=(k,t=i=0,p=++i**k)=>p>n?t:g(k,t+p*!(n%p))
\$\endgroup\$
2
  • \$\begingroup\$ Since you aren't recursing, why not n=>k=>? +1. \$\endgroup\$
    – Yytsi
    Feb 12, 2017 at 9:51
  • \$\begingroup\$ @TuukkaX I came up with something better. (I actually had this earlier with i as a local, which costs 4 extra bytes, and forgot that I could abuse i in the same way that I did with my other formulation.) \$\endgroup\$
    – Neil
    Feb 12, 2017 at 10:17
2
+100
\$\begingroup\$

APL (Dyalog Classic), 14 bytes

+/*⍨∘⍳(⊣×0=|)⊢

Try it online!

Takes the power as the left argument and the number as the right. Even at 128-bit precision, the last couple of test cases exceed the max int size.

Explanation:

     ⍳            ⍝ The range 1 to right argument
  *⍨∘             ⍝ Each raised to the power of the left argument
      (     )⊢    ⍝ Apply the train to this and the right argument
       ⊣×         ⍝ Multiply each power
         0=|      ⍝ By if the right argument is divisible by it
+/                ⍝ And sum
\$\endgroup\$
2
\$\begingroup\$

Pip, 15 bytes

$+Ya%_FN(\,a)Eb

Try It Online!

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

PHP, 86 bytes

$n=$argv[1];$k=$argv[2];for($i=1;$i<=$n**(1/$k);$i++)if($n%$i**$k<1)$s+=$i**$k;echo$s;

Try it here !

Breakdown :

$n=$argv[1];$k=$argv[2];       # Assign variables from input
for($i=1;$i<=$n**(1/$k);$i++)  # While i is between 1 AND kth root of n
    if($n%$i**$k<1)            #     if i^k is a divisor of n
        $s+=$i**$k;            #         then add to s
echo$s;                        # echo s (duh!)
\$\endgroup\$
1
  • \$\begingroup\$ golfed, but not tested: for(;$x<$n=$argv[1];)$n%($x=++$i**$argv[2])?:$s+=$x;echo$s; 59 bytes; requires PHP 5.6 or later. \$\endgroup\$
    – Titus
    Feb 12, 2017 at 15:05
1
\$\begingroup\$

CJam, 20 bytes

Probably not optimally golfed, but I don't see any obvious changes to make...

ri:N,:)rif#{N\%!},:+

Try it online!

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

Jelly, 8 bytes

R*³%$ÐḟS

Try it online!

(Credit not mine.)

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

Bash + Unix utilities, 44 bytes

bc<<<`seq "-fx=%.f^$2;s+=($1%%x==0)*x;" $1`s

Try it online!

Test runs:

for x in '40320 1' '40320 2' '40320 3' '40320 4' '40320 5' '40320 6' '40320 7' '40320 8' '46656 1' '46656 2' '46656 3' '46656 4' '46656 5' '46656 6' '46656 7' '1 1' '1 2' '1 3' '1 12' ; do echo -n "$x "; ./sumpowerdivisors $x; done

40320 1 159120
40320 2 850
40320 3 73
40320 4 17
40320 5 33
40320 6 65
40320 7 129
40320 8 1
46656 1 138811
46656 2 69700
46656 3 55261
46656 4 1394
46656 5 8052
46656 6 47450
46656 7 1
1 1 1
1 2 1
1 3 1
1 12 1
\$\endgroup\$
1
\$\begingroup\$

Python, 56 bytes

lambda n,k:sum(j*(j**k**-1%1==n%j)for j in range(1,n+1))

Try it online!

Fairly straightforward. The only noteworthy thing is that j**k**-1%1 always returns a float in [0,1) while n%j always returns a non-negative integer, so they can only be equal if both are 0.

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

Batch, 138 bytes

@set s=n
@for /l %%i in (2,1,%2)do @call set s=%%s%%*n
@set/at=n=0
:l
@set/an+=1,p=%s%,t+=p*!(%1%%p)
@if %p% lss %1 goto l
@echo %t%

Since Batch doesn't have a power operator, I'm abusing set/a as a form of eval. Very slow when k=1. 32-bit integer arithmetic limits the supported values of n and k:

           n   k
  (too slow)   1
 <1366041600   2
 <1833767424   3
 <2019963136   4
 <2073071593   5
 <1838265625   6
 <1801088541   7
 <1475789056   8
 <1000000000   9
 <1073741824  10
 <1977326743  11
  <244140625  12
 <1220703125  13
  <268435456  14
 <1073741824  15
   <43046721  16
  <129140163  17
  <387420489  18
 <1162261467  19
    <1048576  20
           ...
 <1073741824  30
\$\endgroup\$
1
\$\begingroup\$

R, 35 bytes

function(n,k)sum((a=(1:n)^k)*!n%%a)

Try it online!

3 years later, but 6 bytes shorter than the previous R answer.

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

Husk, 10 9 8 bytes

ΣnḊ³m^⁰ḣ

Try it online!

-1 byte from Jo King.

-1 more byte from Jo King.

Explanation

ΣnḊ³m^⁰ḣ
       ḣ range 1..n
    m^⁰  each raised to power k
 n       set intersection with
  Ḋ³     divisors of n
Σ        sum the list
\$\endgroup\$
0
1
\$\begingroup\$

Vyxal, 6 bytes

K:?e↔∑

Try it Online!

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

Japt -x, 9 bytes

ÆvX=pV)*X

Try it

8 bytes

My first pass. Realised as I was about to post it that it's pretty much identical to Oliver's existing solution.

opV f@vX

Try it

ÆvX=pV)*X     :Implicit input of integers U=n & V=k
Æ             :Map each X in the range [0,U)
 v            :  Is U divisible by
  X=          :    Reassign to X
    pV        :    X raised to the power of V
      )       :  End divisibility check
       *X     :  Multiply by X
              :Implicit output of sum of resulting array
\$\endgroup\$
0
\$\begingroup\$

R, 28 bytes direct, 43 bytes for function

if n,k in memory:

sum((n%%(1:n)^k==0)*(1:n)^k)

for a function:

r=function(n,k)sum((n%%(1:n)^k==0)*(1:n)^k)
\$\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.