Skip to content

Instantly share code, notes, and snippets.

@jonahgeorge
Last active August 29, 2015 14:19
Show Gist options
  • Save jonahgeorge/e6d0778ede9b5538eea9 to your computer and use it in GitHub Desktop.
Save jonahgeorge/e6d0778ede9b5538eea9 to your computer and use it in GitHub Desktop.
Project Euler Problems in Go
package main
func Problem1() int {
sum := 0
for i := 0; i < 1000; i++ {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
package main
const UPPER_BOUND = 4000000
func Problem2() int {
// Initialize evenSum at 2 because oneBefore is included in result
evenSum, localSum := 2, 0
twoBefore, oneBefore := 1, 2
for {
localSum = oneBefore + twoBefore
if (localSum > UPPER_BOUND) {
break
}
if localSum % 2 == 0 {
evenSum += localSum
}
// Shift previous variables
twoBefore = oneBefore
oneBefore = localSum
}
return evenSum
}
package main
func Problem3() int {
i := 2
n := 600851475143
for i * i < n {
for n % i == 0 {
n = n / i
}
i += 1
}
return n
}
package main
func isPalindrome(num int) bool {
reversed := 0
n := num
for n > 0 {
reversed = reversed * 10 + n % 10
n = n / 10
}
return reversed == num
}
func Problem4() int {
a, b := 999, 999
sum := 0
flip := true
for {
sum = a * b
if isPalindrome(sum) {
return sum
}
// Iterate variables
if flip {
a -= 1
} else {
b -= 1
}
flip = !flip
}
}
package main
func isDivisible(num int) bool {
for i := 1; i < 21; i++ {
if num % i != 0 {
return false
}
}
return true
}
func Problem5() int {
n := 0
for {
n += 1
if isDivisible(n) {
return n
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment