Skip to content

Instantly share code, notes, and snippets.

@harrisj
Created April 20, 2017 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harrisj/2b2aadbf3c15d46045b5b93abb2d07d6 to your computer and use it in GitHub Desktop.
Save harrisj/2b2aadbf3c15d46045b5b93abb2d07d6 to your computer and use it in GitHub Desktop.
Adding even numbers between 1 and 100
Go
total := 0
for i := range 100 {
if i % 2 == 0 {
total = total + i
}
}
Rust
let evens = (0..100).filter(|&x| x % 2 == 0);
let total = evens.fold(0, |sum, x| sum + x);
Python
total = sum([i for i in range(100) if x % 2 == 0])
Ruby
total = (1..100).select(:even?).reduce(:+)
Clojure
(+ (range 0 101 2))
Javascript
var total = 0;
for (var i = 1; i <= 100; i++) {
if (i % 2 == 0) {
total += i;
}
}
Haskell
evens = [ x | x <- [1..100], even x]
total = sum evens
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment