36
\$\begingroup\$

The derivative of a function is a cornerstone of mathematics, engineering, physics, biology, chemistry, and a large number of other sciences as well. Today we're going to be calculating something only tangentially related: the arithmetic derivative.

Definition

The arithmetic derivative a(n) or n' is defined here (A003415) by a number of properties that are similar to the derivative of a function.

  • a(0) = a(1) = 0,
  • a(p) = 1, where p is any prime, and
  • a(mn) = m*a(n) + n*a(m).

The third rule is based on the product rule for differentiation of functions: for functions f(x) and g(x), (fg)' = f'g + fg'. So with numbers, (ab)' = a'b + ab'.

Also of note, since the arithmetic derivative can be extended to the negative numbers via this simple relation, a(-n) = -a(n), the input may be negative.

Rules

  • Write a program or function that, given any integer n, returns the arithmetic derivative of n.
  • Inputs will be -230 < n < 230, to avoid problems with integer sizes and numbers too large to factor in a reasonable amount of time. Your algorithm should still be able to theoretically calculate the arithmetic derivative of numbers outside this range.
  • Built-ins for symbolic math, prime factorization and differentiation are allowed.

Examples

> a(1)
0
> a(7)
1
> a(14)   # a(7)*2 + a(2)*7 = 1*2 + 1*7 = 9
9
> a(-5)   # a(-5) = -a(5) = -1
-1
> a(8)    # a(8) = a(2**3) = 3*2**2 = 12
12
> a(225)  # a(225) = a(9)*25 + a(25)*9 = 6*25 + 10*9 = 150 + 90 = 240
240
> a(299792458)  # a(299792458) = a(2)*149896229 + a(7)*42827494 + a(73)*4106746 + a(293339)*1022 = 1*149896229 + 1*42827494 + 1*4106746 + 1*1022 = 149896229 + 42827494 + 4106746 + 1022 = 196831491
196831491

As always, if the problem is unclear, please let me know. Good luck and good golfing!

\$\endgroup\$
3
  • \$\begingroup\$ What, exactly, is prime in a(prime)? Is it just a prime number? \$\endgroup\$
    – Stackstuck
    Commented Apr 17, 2019 at 20:03
  • \$\begingroup\$ Also, I don't get how you decomposed the last example. \$\endgroup\$
    – Stackstuck
    Commented Apr 17, 2019 at 20:20
  • \$\begingroup\$ @Stackstuck Yes, it's any prime. I've edited for clarity. Also, I added to the last example to hopefully make it clearer. \$\endgroup\$
    – Sherlock9
    Commented Apr 18, 2019 at 6:31

22 Answers 22

11
\$\begingroup\$

MATL, 12 bytes

|1>?GtYf/s}0

Try it online!

Explanation

Consider an integer a with |a|>1, and let the (possibly repeated) prime factors of |a| be f1, ..., fn. Then the desired result is a·(1/f1 + ... + 1/fn).

|1>     % take input's absolute value. Is it greater than 1?
?       % if so:
  Gt    %   push input twice
  Yf    %   prime factors. For negative input uses its absolute value
  /     %   divide element-wise
  s     %   sum of the array
}       % else:
  0     %   push 0
\$\endgroup\$
5
  • \$\begingroup\$ Isn't the sum of the prime factors of 1 equal to 0? Or doesn't that work in MATL? \$\endgroup\$
    – wythagoras
    Commented Apr 3, 2016 at 14:18
  • \$\begingroup\$ @wythagoras Actually 1 gives 1 as its "prime" number decomposition. It's a strange result (an empty array would be more meaningful). But that's how Matlab works. And also CJam. So I guess there must be good reason to output 1 in that case? What do you think? I've been tempted to redefine the Yf function to output an empty array for 1, but I wasn't sure \$\endgroup\$
    – Luis Mendo
    Commented Apr 3, 2016 at 15:23
  • 1
    \$\begingroup\$ Pyth gives an empty array, fwiw. \$\endgroup\$
    – isaacg
    Commented Apr 5, 2016 at 4:34
  • \$\begingroup\$ @isaacg Thanks! Maybe I'll change that \$\endgroup\$
    – Luis Mendo
    Commented Apr 5, 2016 at 8:35
  • \$\begingroup\$ Same in Mathematica (was almost a problem once) \$\endgroup\$ Commented Apr 8, 2016 at 4:28
9
\$\begingroup\$

Python, 59 bytes

f=lambda n,p=2:+(n*n>1)and(n%p and f(n,p+1)or p*f(n/p)+n/p)

A recursive function. On large inputs, it runs out of stack depth on typical systems unless you run it with something like Stackless Python.

The recursive definition is implemented directly, counting up to search for candidate prime factors. Since f(prime)=1, if n has a prime p as a factor, we have f(n) == p*f(n/p)+n/p.

\$\endgroup\$
2
  • \$\begingroup\$ Don't you need input and print? At least when I run this (Python 2), I get no result. \$\endgroup\$
    – wythagoras
    Commented Apr 3, 2016 at 18:05
  • \$\begingroup\$ @wythagoras By default, functions are allowed as an alternative to programs. Also, this challenge says "program or function". \$\endgroup\$
    – xnor
    Commented Apr 3, 2016 at 18:14
8
\$\begingroup\$

Jelly, 8 7 bytes

-1 byte by @Dennis

ÆfḟṠ³:S

Uses the same formula everyone else does. However, there's a little trick to deal with 0.

o¬AÆfİS×     Main link. Inputs: n
o¬             Logical OR of n with its logical NOT
               That is, 0 goes to 1 and everything else goes to itself.
  A            Then take the absolute value
   Æf          get its list of prime factors
     İ         divide 1 by those
      S        sum
       ×       and multiply by the input.

Try it here.

\$\endgroup\$
3
  • \$\begingroup\$ Can you please add an explanation? I like answers to have explanations before I upvote them. \$\endgroup\$
    – Sherlock9
    Commented Apr 3, 2016 at 19:10
  • \$\begingroup\$ @Sherlock9 Done. \$\endgroup\$
    – lirtosiast
    Commented Apr 3, 2016 at 21:51
  • \$\begingroup\$ I see that your answer has been golfed and the explanation is now out-of-date. Would you please fix that? Thanks :D \$\endgroup\$
    – Sherlock9
    Commented Apr 12, 2016 at 6:01
5
\$\begingroup\$

Python 2, 87 78 76 74 bytes

a=b=input()
d=2
s=0
while d<=abs(b):
    if a%d==0:
        a=a/d
        s+=b/d
    else:
        d+=1
print s

Improvements thanks to @Maltysen:

a=b=input()
d=2
s=0
while d<=abs(b):
    if a%d==0:a/=d;s+=b/d
    else:d+=1
print s

Further improvement by two bytes:

a=b=input()
d=2
s=0
while abs(a)>1:
    if a%d<1:a/=d;s+=b/d
    else:d+=1
print s

Further improvement thanks to @xnor:

a=b=input()
d=2
s=0
while a*a>1:
    if a%d<1:a/=d;s+=b/d
    else:d+=1
print s

Explanation

The arithmetic derivative of a is equal to a times the sum of the reciprocals of the prime factors of a. No exception for 1 is needed since the sum of the reciprocals of the prime factors of 1 is zero.

\$\endgroup\$
4
  • \$\begingroup\$ abs(a)>1 can be a*a>1. \$\endgroup\$
    – xnor
    Commented Apr 3, 2016 at 17:22
  • \$\begingroup\$ @xnor Yes, thank you. \$\endgroup\$
    – wythagoras
    Commented Apr 3, 2016 at 17:27
  • \$\begingroup\$ Replace line 2 with d,s = 2,0 \$\endgroup\$ Commented Apr 4, 2016 at 12:42
  • \$\begingroup\$ @AgnishomChattopadhyay Both are 8 bytes in total. \$\endgroup\$
    – wythagoras
    Commented Apr 4, 2016 at 15:44
4
\$\begingroup\$

Haskell, 203 90 bytes

Thanks @nimi!

I still have no idea when what indentations cause what interpretation, this is the shortest I managed so far, and as always, I'm sure it can be golfed a lot more. I'm going to try again in the evening.

n#(x:_)|y<-div n x=x*a y+y*a x;_#_=1
a n|n<0= -a(-n)|n<2=0|1<2=n#[i|i<-[2..n-1],mod n i<1]
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Thank you very much, teacher=) I can always learn so much whenever you help me out here! Feel free to add your version as your own answer! \$\endgroup\$
    – flawr
    Commented Apr 3, 2016 at 15:35
4
\$\begingroup\$

J, 30 27 19 chars

Thanks to @Dennis for chopping off 3 characters.

Thanks to @Zgarb for chopping off 8 characters.

0:`(*[:+/%@q:@|)@.*

Try it online!

Sample input:

0:`(*[:+/%@q:@|)@.* _8
_12

0:`(*[:+/%@q:@|)@.* 0
0

0:`(*[:+/%@q:@|)@.* 8
12

How it works:

0:`(*[:+/%@q:@|)@.* N
XX`[email protected]   if Z then Y else X end
0:                        X:  return 0
                  Z       Z:  signum(N)
   (*[:+/%@q:@|)          Y:  N*add_all(reciprocal_all(all_prime_factors(abs(N))))
                              N
    *                          *
      [:+/                      add_all(                                         )
          %@                            reciprocal_all(                         )
            q:@                                       all_prime_factors(      )
               |                                                        abs( )
                                                                            N
\$\endgroup\$
3
\$\begingroup\$

Pyth - 10 8 bytes

Lovin' the implicit input! Should bring it on par with Jelly for most things (Except Dennis' golfing skills).

*scL1P.a

Test Suite.

*             Times the input, implicitly (This also adds the sign back in)
 s            Sum
  cL1         Reciprocal mapped over lit
   P          Prime factorization
    .a        Absolute value of input, implicitly
\$\endgroup\$
3
\$\begingroup\$

Haskell, 59 bytes

n%p|n*n<2=0|mod n p>0=n%(p+1)|r<-div n p=r+p*r%2
(%2)

Implements the recursive definition directly, with an auxiliary variable p that counts up to search for potential prime factors, starting from 2. The last line is the main function, which plugs p=2 to the binary function defined in the first line.

The function checks each case in turn:

  • If n*n<2, then n is one of -1,0,1, and the result is 0.
  • If n is not a multiple of p, then increment p and continue.
  • Otherwise, express n=p*r, and by the "derivative" property, the result is r*a(p)+p*a(r), which simplifies to r+p*a(r) because p is prime.

The last case saves bytes by binding r in a guard, which also avoids the 1>0 for the boilerplate otherwise. If r could be bound earlier, the second condition mod n p>0 could be checked as r*p==n, which is 3 bytes shorter, but I don't see how to do that.

\$\endgroup\$
3
+200
\$\begingroup\$

Japt -x, 16 13 10 bytes

ÒU©a k £/X

- 6 bytes thanks to @Shaggy

Try it online!

\$\endgroup\$
8
  • \$\begingroup\$ Both fail for negative numbers because, for some reason, N.k() doesn't work on them. \$\endgroup\$
    – Shaggy
    Commented Feb 28, 2019 at 16:54
  • \$\begingroup\$ Here's a fix, with some golfing. \$\endgroup\$
    – Shaggy
    Commented Feb 28, 2019 at 16:58
  • \$\begingroup\$ Or -2 more byes with the -x flag. \$\endgroup\$
    – Shaggy
    Commented Feb 28, 2019 at 16:59
  • \$\begingroup\$ Knocked another byte off \$\endgroup\$
    – Shaggy
    Commented Feb 28, 2019 at 18:10
  • \$\begingroup\$ @Shaggy Thanks, nice \$\endgroup\$
    – Quintec
    Commented Feb 28, 2019 at 19:26
3
+100
\$\begingroup\$

APL (Dyalog Extended), 13 9 bytes

A simple solution. The Dyalog Unicode version was simply a longer version of this so it has been omitted.

Edit: Saved 4 bytes by adopting the method in lirtosiast's Jelly solution.

{+/⍵÷⍭|⍵}

Try it online!

Ungolfing

{+/⍵÷⍭|⍵}

{        }  A dfn, a function in {} brackets.
     ⍭|⍵   The prime factors of the absolute value of our input.
   ⍵÷      Then divide our input by the above array,
            giving us a list of products for the product rule.
 +/         We sum the above numbers, giving us our arithmetic derivative.
\$\endgroup\$
2
\$\begingroup\$

Ruby, 87 66 80 75 70 68 bytes

This answer is based on Luis Mendo's MATL answer, wythagoras's Python answer, and the idea that the arithmetic derivative of a number m is equal to m·(1/p1 + 1/p2 + ... + 1/pn) where p1...pn is every prime factor of n to multiplicity.

->n{s=0;(2...m=n.abs).map{|d|(m/=d;s+=n/d)while m%d<1};m<2?0:s+0**s}

This function is called in the following way:

> a=->n{s=0;(2...m=n.abs).map{|d|(m/=d;s+=n/d)while m%d<1};m<2?0:s+0**s}
> a[299792458]
196831491

Ungolfing:

def a(n)
  s = 0
  m = n.abs
  (2...m).each do |z|
    while m%d == 0
      m /= d
      s += n / d
    end
  end
  if s == 0
    if n > 1
      s += 1 # if s is 0, either n is prime and the while loop added nothing, so add 1
             # or n.abs < 2, so return 0 anyway
             # 0**s is used in the code because it returns 1 if s == 0 and 0 for all other s
    end
  end
  return s
end
\$\endgroup\$
2
\$\begingroup\$

Julia, 72 43 bytes

n->n^2>1?sum(p->n÷/(p...),factor(n^2))/2:0

This is an anonymous function that accepts an integer and returns a float. To call it, assign it to a variable.

For an input integer n, if n2 ≤ 1 return 0. Otherwise obtain the prime factorization of n2 as a Dict, then for each prime/exponent pair, divide the prime by its exponent, then divide n by the result. This is just computing n x / p, where p is the prime factor and x is its exponent, which is the same as summing n / p, x times. We sum the resulting array and divide that by 2, since we've summed twice as much as we need. That's due to the fact that we're factoring n2 rather than n. (Doing that is a byte shorter than factoring |n|.)

Saved 29 bytes thanks to Dennis!

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

Seriously, 17 14 11 12 bytes

My first ever Seriously answer. This answer is based on Luis Mendo's MATL answer and the idea that the arithmetic derivative of a number m is equal to m·(1/p1 + 1/p2 + ... + 1/pn) where p1...pn is every prime factor of n to multiplicity. My addition is to note that, if m = p1e1·p2e2·...·pnen, then a(m) = m·(e1/p1 + e2/p2 + ... + en/pn). Thanks to Mego for golfing and bug fixing help. Try it online!

,;w`i@/`MΣ*l

Ungolfing:

,             get a single input
 ;w           duplicate input and get prime factorization, p_f
               for input [-1..1], this returns [] and is dealt with at the end
   `   `M     map the function inside `` to p_f
    i         pop all elements of p_f[i], the prime and the exponent, to the stack
     @        rotate so that the exponent is at the top of the stack
      /       divide the exponent by the prime
         Σ    sum it all together
          *   multiply this sum with the input
           l  map and multiply do not affect an empty list, so we just take the length, 0
               l is a no-op for a number, so the result is unchanged for all other inputs
\$\endgroup\$
0
1
\$\begingroup\$

Jolf, 13 bytes

*jmauΜm)jd/1H

Kudos to the MATL answer for the algorithm! Try it here, or test them all at once. (Outputs [key,out] in an array.)

Explanation

*jmauΜm)jd/1H
*j             input times
      m)j         p.f. of input
     Μ   d/1H      mapped to inverse
    u            sum of
  ma            abs of
\$\endgroup\$
1
\$\begingroup\$

Mathematica 10.0, 39 bytes

Tr[If[#>1,#2/#,0]&@@@FactorInteger@#]#&
\$\endgroup\$
7
  • 1
    \$\begingroup\$ Can you please add an explanation? I like answers to have explanations before I upvote them. \$\endgroup\$
    – Sherlock9
    Commented Apr 4, 2016 at 9:31
  • 1
    \$\begingroup\$ @Sherlock9 This is a quite uninteresting answer so I don't plan to add one. It's OK if no one upvotes it. \$\endgroup\$
    – feersum
    Commented Apr 4, 2016 at 10:24
  • \$\begingroup\$ Alright, then. Have a good day :) \$\endgroup\$
    – Sherlock9
    Commented Apr 4, 2016 at 10:25
  • \$\begingroup\$ In the current Mathematica version, FactorInteger@1 yields {1,1}, so the If function is no longer necessary, saving 10 bytes. \$\endgroup\$ Commented Aug 26, 2016 at 5:52
  • \$\begingroup\$ @GregMartin Seriously? That's even more inconsistent than the value, {{1,1}}, returned by my version ({} is the expected result to me). \$\endgroup\$
    – feersum
    Commented Aug 26, 2016 at 6:31
1
\$\begingroup\$

APL(NARS), 35 char, 70 bytes

{1≥a←∣⍵:0⋄1=≢k←πa:×⍵⋄c+m×∇c←⍵÷m←↑k}

test and how to use:

  f←{1≥a←∣⍵:0⋄1=≢k←πa:×⍵⋄c+m×∇c←⍵÷m←↑k}
  f 14
9
  f 8
12
  f 225
240
  f ¯5
¯1
  f 299792458
196831491

I thought that it would not be ok because I don't know if c variable is composed (and not a prime)... But seems ok for the test...

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

05AB1E, 7 4 bytes

ÄÒ÷O

Port of @lirtosiast's Jelly answer.

Try it online or verify all test cases.

Explanation:

Ä     # Take the absolute value of the (implicit) input
 Ò    # Get all its prime factors (with duplicates)
  ÷   # Integer divide the (implicit) input by each of these prime factors
   O  # And take the sum (which is output implicitly)
\$\endgroup\$
1
\$\begingroup\$

Vyxal s, 3 bytes

ȧǐ/

Try it Online!

ȧ   # Abs. val
 ǐ  # All prime factors
    # (Implicit input)
  / # Divided by each factor.  
    # (s flag) sum of stack

-1 thx to Underslash

\$\endgroup\$
2
  • \$\begingroup\$ 3 bytes -s If you remove the -r flag, you can get implicit input for the dividing. \$\endgroup\$
    – Underslash
    Commented May 30, 2021 at 4:21
  • \$\begingroup\$ @Underslash Thx! \$\endgroup\$
    – emanresu A
    Commented May 30, 2021 at 5:38
1
\$\begingroup\$

Pari/GP, 44 bytes

n->n*vecsum([i[2]/p|i<-factor(n)~,0<p=i[1]])

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Perl 5, 62 bytes

perl -MMath::Prime::Util=:all -E"map$i+=1/$_,factor abs($j=<>);say$i*$j"

Uses the formula (from OEIS): If n = Product p_i^e_i, a(n) = n * Sum (e_i/p_i).

\$\endgroup\$
0
\$\begingroup\$

Perl 6, 90

sub A(\n) {0>n??-A(-n)!!(n>1)*{$_??n/$_*A($_)+$_*A n/$_!!1}(first n%%*,2..^n)};say A slurp

This might be a bit slow for large numbers. Replace 2..^n with 2..n.sqrt for longer code but faster computation.

\$\endgroup\$
0
\$\begingroup\$

Ink, 183 bytes

==function a(n)
{n<0:
~return-a(-n)
}
{n<2:
~return 0
}
~temp f=t(n,2)
{f:
~return a(n/f)*f+n/f
}
~return 1
==function t(n,i)
{n>1&&n-i:
{n%i:
~return t(n,i+1)
}
~return i
}
~return 0

Try it online!

I refuse to believe this is a good solution, but I can't see a way to improve it either.

\$\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.