Last active
January 25, 2021 15:38
-
-
Save tomaslibal/4468743 to your computer and use it in GitHub Desktop.
A simple implementation of Euler's totient function ("Phi function"). More info about the function at http://mathworld.wolfram.com/TotientFunction.html. The language used here in this implementation is R (r-base-core 2.15.1-5ubuntu1).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Eulers Totient Function | |
# | |
# Description at http://mathworld.wolfram.com/TotientFunction.html | |
# Algorithm based on http://en.wikipedia.org/wiki/Euler%27s_totient_function | |
# Interesting property: for a prime number p, epf(p) = p - 1 | |
# greatest common divisor of two integers | |
# @param m int the first number | |
# @param n int the second number | |
# @return int the greates common divisor of the two numbers | |
# inspired by a post at http://mathforum.org/library/drmath/view/51893.html | |
# <input> M=44305 N=42355 | |
# rem = 1950 (44305 mod 42355) | |
# rem = 1405 (42355 mod 1950) | |
# rem = 545 ( 1950 mod 1405) | |
# ... | |
# rem = 0 ( 10 mod 5) | |
# <output> 5 | |
gcd <- function (m, n) { | |
while (1) { | |
rem <- m %% n # calculate the remainder here | |
ifelse (rem == 0, break, { m = n; n = rem; }) # if the remainder is greater than 0 then we continue by changing m to the value of n and n to the value of the remainder | |
} | |
n | |
} | |
# eulers phi function | |
# @param n int number - the "phi of n" | |
# @return int the function's value for the given number | |
epf <- function (n) { | |
if (n < 0) { -1 } # function's domain are positive integers only | |
sum = 0 | |
for (k in 1:n) { # epf(n) is number of positive integers in 1 <= k <= n | |
if (gcd(n, k) == 1) { sum = sum + 1 } # for which gcd (n, k) is equal 1. (when gcd (n, k) is 1, the number | |
} # k is a totient of n. And epf(n) is the sum of these totients (numbers relatively prime to n) | |
sum # return the result | |
} | |
# DEMO of epf(n) for a range from 1 to 100 | |
vals <- NULL | |
for (i in 1:100) { | |
vals <- c(vals, epf(i)) | |
} | |
plot(vals) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment