What I learned by solving 30 Project Euler problems in 50 days
Learning to code by solving computational math problems.
From 2023-05-22 to 2023-07-10[1], I solved 30 computational math problems from Project Euler. Here's a summary of what I learned.
- What is Project Euler? It's a database of math problems that require code to solve. Some example problems:
- Problem #4: Find the largest palindrome made from the product of two three-digit numbers.
- Problem #17: If all the numbers from 1 to 1000 (inclusive) were written out in words, how many letters would be used?
- Problem #25: Find the index of the first term in the Fibonacci sequence that contains 1000 digits.
- What tech did you use? I used Zed, Go, and GitHub to solve the problems.[2]
- Can I see example code you wrote? Yes! Here's my code for Problem #15:[3]
package main import ( "fmt" "math/big" ) func factorial_of_number(number int64) *big.Int { // BigInts are required – instead of int64 – because the factorial of // numbers > 30 exceeds the integer limit for int64. product := big.NewInt(1) for i := 1; i <= int(number); i++ { product.Mul(product, big.NewInt(int64(i))) } return product } func main() { // funnily enough, I came up with this problem myself! I remembered some vague answer / way to use combinatorics // and after some pain importing the combin package, I figured out that on an LxL board, running the combination // nCr (where) n = 2L and r = L gives the correct answer experimentally. there's probably a better way to do this, // but I cannot be bothered. I made a whole Math StackExchange post on it too. var L int64 = 20 final_numerator := factorial_of_number(2 * L) // the numerator is 40! denominator1 := factorial_of_number(L) denominator2 := factorial_of_number(L) final_denominator := big.NewInt(0) final_denominator.Mul(denominator1, denominator2) valid_paths_on_a_LxL_board := big.NewInt(0) valid_paths_on_a_LxL_board.Div(final_numerator, final_denominator) fmt.Println(valid_paths_on_a_LxL_board) }
- Ok so what actually did you learn? A lot of things, actually!
- How to use Unix and Git commands
- How to structure a Go file (with package and import declarations)
- Different data types (int, string, bool, etc.)
- Basic Go constructs (if / else-if / else statements, for loops, slices, maps)
- How to create a good function (with appropriate inputs and outputs)
- How to write succinct yet descriptive code comments
- How to maintain consistent style (in terms of naming and whitespace)
- Do you have any advice following this project? I certainly have some advice if you want to learn to code:
- Code every day. It's very hard to get back into the 'flow' of coding if you skip coding for a few days.
- The only way to learn how to code is to write code, and it also happens to be the most efficient way. Don't spend too much time just reading tutorials on how to code.
- Don't be afraid to ask the internet for help. Everybody does it.