August 26, 2024

P34 - Calculate Euler's totient function phi(m).

Euler's so-called totient function phi(m) is defined as the number of positive integers r (1 <= r <= m) that are coprime to m.

> 10.totient()
4

kotlin

package org.kotlin99.arithmetic

import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.junit.Test

fun Int.totient() = (1..this).filter { it.isCoprimeTo(this) }.size

class P34Test {
    @Test fun `calculate Euler's totient function`() {
        assertThat(10.totient(), equalTo(4))
        assertThat(10090.totient(), equalTo(4032))
    }
}
Be first to comment
Leave a reply