Skip to content

Commit a106bb9

Browse files
PraneethJainappgurueu
authored andcommitted
Add Euler totient
1 parent 5826b38 commit a106bb9

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

.spec/math/totient_spec.lua

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
describe("Totient", function()
2+
local totient = require("math.totient")
3+
it("should handle edge cases", function()
4+
assert.equal(1, totient(1))
5+
end)
6+
7+
it("totient of prime p should be p - 1", function()
8+
assert.equal(1, totient(2))
9+
assert.equal(2, totient(3))
10+
assert.equal(4, totient(5))
11+
assert.equal(78, totient(79))
12+
assert.equal(96, totient(97))
13+
end)
14+
15+
it("should handle general cases", function()
16+
assert.equal(2, totient(4))
17+
assert.equal(12, totient(42))
18+
assert.equal(36, totient(63))
19+
assert.equal(24, totient(72))
20+
assert.equal(40, totient(100))
21+
end)
22+
end)

LICENSE

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
MIT License
22

3-
Copyright (c) 2023 Lars Müller
3+
Copyright (c) 2023 Lars Müller and contributors
44

55
Permission is hereby granted, free of charge, to any person obtaining a copy
66
of this software and associated documentation files (the "Software"), to deal

src/math/totient.lua

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
local gcd = require("math.greatest_common_divisor")
2+
3+
return function(
4+
n -- number
5+
)
6+
local totient = 0
7+
for i = 1, n do
8+
if gcd(i, n) == 1 then -- relatively prime?
9+
totient = totient + 1
10+
end
11+
end
12+
return totient -- number of positive integers less than n that are relatively prime to n
13+
end

0 commit comments

Comments
 (0)