84 lines
1.9 KiB
Plaintext
84 lines
1.9 KiB
Plaintext
class Prime {
|
|
static subfactors(n, p) {
|
|
var subfactors = []
|
|
|
|
var q = n / p
|
|
var r = n % p
|
|
|
|
while (r == 0) {
|
|
subfactors.add(p)
|
|
n = q
|
|
q = n / p
|
|
r = n % p
|
|
}
|
|
|
|
return [n, subfactors]
|
|
}
|
|
|
|
static trial_factorization(n) {
|
|
var factors = []
|
|
|
|
var subfactor_result = subfactors(n, 2)
|
|
n = subfactor_result[0]
|
|
Utility.extend_list(factors, subfactor_result[1])
|
|
|
|
subfactor_result = subfactors(n, 3)
|
|
n = subfactor_result[0]
|
|
Utility.extend_list(factors, subfactor_result[1])
|
|
|
|
var p = 5
|
|
while (p * p <= n) {
|
|
subfactor_result = subfactors(n, p)
|
|
n = subfactor_result[0]
|
|
Utility.extend_list(factors, subfactor_result[1])
|
|
p = p + 2
|
|
|
|
subfactor_result = subfactors(n, p)
|
|
n = subfactor_result[0]
|
|
Utility.extend_list(factors, subfactor_result[1])
|
|
p = p + 4
|
|
}
|
|
|
|
if (n >= 1) { factors.add(n) }
|
|
return factors
|
|
}
|
|
|
|
static prime_factors(integer) {
|
|
return trial_factorization(integer)
|
|
}
|
|
}
|
|
|
|
class Utility {
|
|
static cons(x, xs) {
|
|
return extend_list([x], xs)
|
|
}
|
|
|
|
static extend_list(list_one, list_two) {
|
|
for (element in list_two) {
|
|
list_one.add(element)
|
|
}
|
|
return list_one
|
|
}
|
|
|
|
static palindrome(n) {
|
|
var result = true
|
|
var num = n.toString
|
|
for (i in (0..(num.count-1)/2)) {
|
|
if (num.codePoints[i] != num.codePoints[num.count-1-i]) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
static max(sequence) {
|
|
var max = sequence.take(1).toList[0]
|
|
for (element in sequence) {
|
|
if (element > max) {
|
|
max = element
|
|
}
|
|
}
|
|
|
|
return max
|
|
}
|
|
} |