-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsmarandache_function.jl
More file actions
88 lines (61 loc) · 1.58 KB
/
smarandache_function.jl
File metadata and controls
88 lines (61 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/julia
# Trizen
# 17 September 2016
# https://github.com/trizen
# A decently efficient algorithm for computing the results of the Kempner/Smarandache function.
# See also: https://projecteuler.net/problem=549
# https://en.wikipedia.org/wiki/Kempner_function
# https://mathworld.wolfram.com/SmarandacheFunction.html
# ∑S(i) for 2 ≤ i ≤ 10^2 == 2012
# ∑S(i) for 2 ≤ i ≤ 10^6 == 64938007616
# ∑S(i) for 2 ≤ i ≤ 10^8 == 476001479068717
using Primes
function smarandache(n::Int64, cache)
isprime(n) && return n
f = factor(n)
count = 0
distinct = true
for v in values(f)
count += v
if (distinct && v != 1)
distinct = false
end
end
distinct && return maximum(keys(f))
if (length(f) == 1)
k = collect(keys(f))[1]
(count <= k) && return k*count
if haskey(cache, n)
return cache[n]
end
max = k*count
ff = factorial(BigInt(max - k))
while (ff % n == 0)
max -= k
ff /= max
end
cache[n] = max
return max
end
arr = Int64[]
for (k,v) in f
push!(arr, v == 1 ? k : smarandache(k^v, cache))
end
maximum(arr)
end
#
## Tests
#
function test()
cache = Dict{Int64, Int64}()
limit = 10^2
sumS = 0
for k in 2:limit
sumS += smarandache(k, cache)
end
println("∑S(i) for 2 ≤ i ≤ $limit == $sumS")
if (limit == 100 && sumS != 2012)
warn("However that is incorrect! (expected: 2012)")
end
end
test()