Project Euler 1 in Several Languages
UPDATE May 13, 2015: Wow, look at the Jekyll code support!
Here’s some code to answer Project Euler 1 in a few languages.
By the way, you do not need code to solve this problem…
(1) Java:
public class pe1 {
public static void main(String[] args) {
int total = 0;
for (int i = 3; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
total += i;
}
}
System.out.println(total);
}
}
(2) Python:
total = 0
for i in range(1000):
if i % 3 == 0 or i % 5 == 0:
total += i
print(total)
(Alternatively, the one-liner below is probably “better”.)
print(sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0))
(3) C++:
#include <iostream>
int main() {
int total = 0;
for (int i = 3; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
total += i;
}
}
std::cout << total << std::endl;
return 0;
}
(4) Scala:
object HelloWorld {
def main(args: Array[String]): Unit = {
var result : Int = 0
for (a <- 1 until 1000) {
if (a % 3 == 0 || a % 5 == 0) {
result += a;
}
}
println(a)
}
}
Note to self for Scala: to means it includes the last value, until means it does not.