Restructure
This commit is contained in:
78
programs/euler.kl
Normal file
78
programs/euler.kl
Normal file
@@ -0,0 +1,78 @@
|
||||
// @todo: Add more stats in the preview
|
||||
// @todo: for 0..1000(implicit i) and for i in 0..1000
|
||||
// @todo: Add blocks of stmts that you can simply define inside a function etc.
|
||||
|
||||
entry :: ()
|
||||
print_str("\n")
|
||||
euler1()
|
||||
euler3()
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Euler 2
|
||||
//-----------------------------------------------------------------------------
|
||||
euler1 :: ()
|
||||
end := 1000
|
||||
result := 0
|
||||
for i := 0, i < end, i++
|
||||
if i % 3 == 0
|
||||
result += i
|
||||
else if i % 5 == 0
|
||||
result += i
|
||||
print_str("Euler1: ")
|
||||
print_int(result)
|
||||
print_str("\n")
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Euler 3
|
||||
//-----------------------------------------------------------------------------
|
||||
int_sqrt :: (s: S64): S64
|
||||
result := sqrt(cast(s: F64))
|
||||
return cast(result: S64)
|
||||
|
||||
// https://en.wikipedia.org/wiki/Integer_square_root
|
||||
int_sqrt1 :: (s: S64): S64
|
||||
x0 := s / 2
|
||||
|
||||
if x0 != 0
|
||||
x1 := (x0 + s / x0) / 2
|
||||
for x1 < x0
|
||||
x0 = x1
|
||||
x1 = (x0 + s / x0) / 2
|
||||
return x0
|
||||
else
|
||||
return s
|
||||
|
||||
euler3 :: ()
|
||||
n := 600851475143
|
||||
results: [32]S64
|
||||
results_len := 0
|
||||
|
||||
// First search all 2's
|
||||
for n % 2 == 0
|
||||
results[results_len++] = 2
|
||||
n /= 2
|
||||
|
||||
// Then search other primes, 3, 5, 7 etc.
|
||||
for i := 3, i <= int_sqrt1(n), i += 2
|
||||
for n % i == 0
|
||||
results[results_len++] = i
|
||||
n /= i
|
||||
|
||||
// Then check if our number is a prime it self
|
||||
if n > 2
|
||||
results[results_len++] = n
|
||||
|
||||
print_str("Euler3: ")
|
||||
|
||||
is_correct: S64 = 1
|
||||
for i := 0, i < results_len, i++
|
||||
is_correct = is_correct * results[i]
|
||||
print_int(is_correct)
|
||||
|
||||
print_str(":: ")
|
||||
print_int(is_correct)
|
||||
|
||||
sqrt :: (v: F64): F64 #foreign
|
||||
print_int :: (i: S64) #foreign
|
||||
print_str :: (i: String) #foreign
|
||||
Reference in New Issue
Block a user