diff --git a/v/euler/euler.v b/v/euler/euler.v new file mode 100644 index 0000000..405b57f --- /dev/null +++ b/v/euler/euler.v @@ -0,0 +1,64 @@ +module euler +import math + +pub fn range(start int, end int) []int { + mut result := []int + for i := start; i <= end; i++ { + result << i + } + return result +} + +pub fn even(n int) bool { + return n % 2 == 0 +} + +pub fn prime(n u64) bool { + for i := u64(2); i <= u64(math.sqrt(f64(n))); i++ { + if n % i == 0 { + return false + } + } + return true +} + +pub fn factors(n u64) []u64 { + mut factors := []u64 + for i := u64(2); i <= u64(math.sqrt(f64(n))); i++ { + if n % i == 0 && prime(i) { + factors << i + } + } + return factors +} + +pub fn max(ints []u64) u64 { + mut max := u64(0) + for n in ints { + if n > max { + max = n + } + } + return max +} + +pub fn two_combinations(ints []int) [][]int { + mut result := [[]int] + result = [] + for i := 0; i < ints.len; i++ { + for j := i + 1; j < ints.len; j++ { + result << [[ints[i], ints[j]]] + } + } + return result +} + +pub fn palindrome(n int) bool { + str := n.str() + for i := 0; i < str.len; i++ { + if str[i] != str[str.len-1-i] { + return false + } + } + return true +} diff --git a/v/euler001.v b/v/euler001.v new file mode 100644 index 0000000..e2e38b3 --- /dev/null +++ b/v/euler001.v @@ -0,0 +1,17 @@ +fn multiples_of_three_and_five_below(n int) []int { + mut nums := []int + for i := 3; i < n; i++ { + if i % 3 == 0 || i % 5 == 0 { + nums << i + } + } + return nums +} + +fn main() { + mut result := 0 + for n in multiples_of_three_and_five_below(1000) { + result += n + } + println(result) +} diff --git a/v/euler002.v b/v/euler002.v new file mode 100644 index 0000000..cd78c5e --- /dev/null +++ b/v/euler002.v @@ -0,0 +1,22 @@ +import euler + +fn even_fibonacci_up_to(n int) []int { + mut result := []int + mut a := 0 + mut b := 1 + for a + b < n { + if euler.even(a + b) { result << a + b } + temp := b + b = a + b + a = temp + } + return result +} + +fn main() { + mut result := 0 + for n in even_fibonacci_up_to(4000000) { + result += n + } + println(result) +} diff --git a/v/euler003.v b/v/euler003.v new file mode 100644 index 0000000..6cf067a --- /dev/null +++ b/v/euler003.v @@ -0,0 +1,5 @@ +import euler + +fn main() { + println(euler.max(euler.factors(600851475143))) +} diff --git a/v/euler004.v b/v/euler004.v new file mode 100644 index 0000000..2432957 --- /dev/null +++ b/v/euler004.v @@ -0,0 +1,13 @@ +import euler + +fn main() +{ + mut max := 0 + for combo in euler.two_combinations(euler.range(100, 999)) { + product := combo[0] * combo[1] + if product > max && euler.palindrome(product) { + max = product + } + } + println(max) +}