Derivatif Aritmatika


Turunan dari suatu fungsi adalah landasan matematika, teknik, fisika, biologi, kimia, dan sejumlah besar ilmu lain juga. Hari ini kita akan menghitung sesuatu yang hanya berhubungan secara tangensial: turunan aritmatika.


Derivatif aritmatika a(n)atau n'didefinisikan di sini ( A003415 ) oleh sejumlah properti yang mirip dengan turunan dari suatu fungsi.

  • a(0) = a(1) = 0,
  • a(p) = 1, di mana pada prime, dan
  • a(mn) = m*a(n) + n*a(m).

Aturan ketiga didasarkan pada aturan produk untuk diferensiasi fungsi: untuk fungsi f(x)dan g(x), (fg)' = f'g + fg'. Begitu juga dengan angka (ab)' = a'b + ab',.

Juga perhatikan, karena turunan aritmatika dapat diperluas ke angka negatif melalui hubungan sederhana ini a(-n) = -a(n), input mungkin negatif.


  • Tulis program atau fungsi yang, dengan bilangan bulat apa pun n, mengembalikan turunan aritmatika dari n.
  • Inputnya adalah -230 < n < 230 , untuk menghindari masalah dengan ukuran bilangan bulat dan angka terlalu besar untuk faktor dalam jumlah waktu yang wajar. Algoritme Anda masih harus dapat menghitung turunan aritmatika angka di luar rentang ini secara teoritis.
  • Built-in untuk matematika simbolik, faktorisasi utama dan diferensiasi diizinkan.


> a(1)
> a(7)
> a(14)   # a(7)*2 + a(2)*7 = 1*2 + 1*7 = 9
> a(-5)   # a(-5) = -a(5) = -1
> a(8)    # a(8) = a(2**3) = 3*2**2 = 12
> a(225)  # a(225) = a(9)*25 + a(25)*9 = 6*25 + 10*9 = 150 + 90 = 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

Seperti biasa, jika masalahnya tidak jelas, beri tahu saya. Semoga berhasil dan bermain golf dengan baik!

Apa tepatnya yang ada primedi a(prime)dalamnya? Apakah itu hanya bilangan prima?

Juga, saya tidak mengerti bagaimana Anda mendekomposisi contoh terakhir.

@ Stackstuck Ya, ini prima. Saya telah mengedit untuk kejelasan. Juga, saya menambahkan contoh terakhir untuk semoga membuatnya lebih jelas.



MATL , 12 byte


Cobalah online!


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

Isn't the sum of the prime factors of 1 equal to 0? Or doesn't that work in MATL?

@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
Luis Mendo

Pyth gives an empty array, fwiw.

@isaacg Thanks! Maybe I'll change that
Luis Mendo

Same in Mathematica (was almost a problem once)


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.

Don't you need input and print? At least when I run this (Python 2), I get no result.

@wythagoras By default, functions are allowed as an alternative to programs. Also, this challenge says "program or function".


Jelly, 8 7 bytes

-1 byte by @Dennis


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.

Can you please add an explanation? I like answers to have explanations before I upvote them.

@Sherlock9 Done.

I see that your answer has been golfed and the explanation is now out-of-date. Would you please fix that? Thanks :D


Python 2, 87 78 76 74 bytes

while d<=abs(b):
    if a%d==0:
print s

Improvements thanks to @Maltysen:

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

Further improvement by two bytes:

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

Further improvement thanks to @xnor:

while a*a>1:
    if a%d<1:a/=d;s+=b/d
print s


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.

abs(a)>1 can be a*a>1.

@xnor Yes, thank you.

Replace line 2 with d,s = 2,0
Agnishom Chattopadhyay

@AgnishomChattopadhyay Both are 8 bytes in total.


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]

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!


J, 30 27 19 chars

Thanks to @Dennis for chopping off 3 characters.

Thanks to @Zgarb for chopping off 8 characters.


Try it online!

Sample input:

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

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

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

How it works:

0:`(*[:+/%@q:@|)@.* N
XX`YYYYYYYYYYYYY@.Z   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))))
    *                          *
      [:+/                      add_all(                                         )
          %@                            reciprocal_all(                         )
            q:@                                       all_prime_factors(      )
               |                                                        abs( )


Pyth - 10 8 bytes

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


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


Haskell, 59 bytes

n%p|n*n<2=0|mod n p>0=n%(p+1)|r<-div n p=r+p*r%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.


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 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!



,             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


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!



{        }  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.


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 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]


def a(n)
  s = 0
  m = n.abs
  (2...m).each do |z|
    while m%d == 0
      m /= d
      s += n / d
  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
  return s


Julia, 72 43 bytes


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!


Mathematica 10.0, 39 bytes


Can you please add an explanation? I like answers to have explanations before I upvote them.

@Sherlock9 This is a quite uninteresting answer so I don't plan to add one. It's OK if no one upvotes it.

Alright, then. Have a good day :)

In the current Mathematica version, FactorInteger@1 yields {1,1}, so the If function is no longer necessary, saving 10 bytes.
Greg Martin

@GregMartin Seriously? That's even more inconsistent than the value, {{1,1}}, returned by my version ({} is the expected result to me).


APL(NARS), 35 char, 70 bytes


test and how to use:

  f 14
  f 8
  f 225
  f ¯5
  f 299792458

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


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).


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.


Ink, 183 bytes

==function a(n)
~return 0
~temp f=t(n,2)
~return a(n/f)*f+n/f
~return 1
==function t(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.

Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.