Somewhere you have to start using a new language. I found it pretty frustrating to invent example code. You can cut corners or be negligent easily. That's why I really love Project Euler. I solved problems here already using many languages: PHP, C, Ruby, Python and Haskell.
It's really either for beginning something or math nerds :) Solving problems I was curious how much of Go's specialties I can use at the beginning. Fortunately there was some, such as the multiple return arguments, or simple variable definition, the dynamic type assignment - or anonym function, as much as it's a specialty, though.
The compiler was pretty helpful telling me where the problems are and what are they. Sublime has Go syntax highlighter so that was my choice of editor.
As a Sunday night bedtime story here you are my first three solutions.
#1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
package main
import "fmt"
func main() {
sum := 0
for i := 3; i < 1000; i++ {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
fmt.Println(sum)
}
#2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
package main
import "fmt"
func main() {
var sum, prev, current uint32 = 0, 0, 1
micfib := func(prev, current uint32) (uint32, uint32) {
return current, current + prev
}
for current < 4e6 {
prev, current = micfib(prev, current)
if current % 2 == 0 {
sum += current
}
}
fmt.Println(sum)
}
#3
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
package main
import "fmt"
func main() {
var div, max uint64 = 2, 600851475143
for div < max {
if max % div == 0 {
max /= div
div = 2
} else {
div++
}
}
fmt.Println(div)
}
---
This weekend I had almost zero time to care about my topics. I really hope soon I'll find some time to dig deeper into Go. I kinda like it, to be honest.
Peter

No comments:
Post a Comment
Note: only a member of this blog may post a comment.