Solved exercises 1 to 3
parent
bcb206349c
commit
8b16126de1
@ -0,0 +1,89 @@
|
||||
package euler
|
||||
|
||||
// SumMultiples finds the sum of all the multiples of 3 or 5 below 1000
|
||||
func SumMultiples() int {
|
||||
result := 0
|
||||
|
||||
for i := range [1000]int{} {
|
||||
if i%3 == 0 || i%5 == 0 {
|
||||
result += i
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// EvenFibonacci finds the sum of the even-valued terms of a Fibonacci sequence,
|
||||
// considering only the terms whose values do not exceed max
|
||||
func EvenFibonacci(max int) int {
|
||||
result := 0
|
||||
first, second := 0, 1
|
||||
|
||||
for second <= max {
|
||||
first, second = second, first+second
|
||||
|
||||
if second%2 == 0 {
|
||||
result += second
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// FindLargestPrimeFactor finds the largest prime factor of the number x
|
||||
func FindLargestPrimeFactor(x int) int {
|
||||
|
||||
isPrime := func(n int) bool {
|
||||
|
||||
// Check if n=1 or n=0
|
||||
if n <= 1 {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check if n=2 or n=3
|
||||
if n == 2 || n == 3 {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check whether n is divisible by 2 or 3
|
||||
if n%2 == 0 || n%3 == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check from 5 to square root of n
|
||||
// Iterate i by (i+6)
|
||||
for i := 5; i*i <= n; i = i + 6 {
|
||||
if n%i == 0 || n%(i+2) == 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if x == 2 || x == 3 {
|
||||
return x
|
||||
}
|
||||
|
||||
for x%2 == 0 {
|
||||
x /= 2
|
||||
}
|
||||
|
||||
for x%3 == 0 {
|
||||
x /= 3
|
||||
}
|
||||
|
||||
largest := 0
|
||||
for i := 5; i <= x; i = i + 1 {
|
||||
if x%i == 0 {
|
||||
for x%i == 0 {
|
||||
x /= i
|
||||
}
|
||||
|
||||
if isPrime(i) {
|
||||
largest = i
|
||||
}
|
||||
}
|
||||
}
|
||||
return largest
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
package euler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSumMultiples(t *testing.T) {
|
||||
fmt.Println(SumMultiples())
|
||||
}
|
||||
|
||||
func TestEvenFibonacci(t *testing.T) {
|
||||
fmt.Println(EvenFibonacci(4_000_000))
|
||||
}
|
||||
|
||||
func TestFindLargestPrimeFactor(t *testing.T) {
|
||||
fmt.Println(FindLargestPrimeFactor(13195))
|
||||
fmt.Println(FindLargestPrimeFactor(600851475143))
|
||||
}
|
||||
Loading…
Reference in New Issue