Project Euler Problem 1

Part 1,2

Project Euler problem 1 wants a person to find the sum of all numbers less than 1000 that are divisible by 3 and 5.  I was able solve this problem pretty easily in Scala.  My solution is very similar to how I would solve the problem in Java.  Quickly glancing at the code, you can see there is less of it.  Keywords in Java like Public and static aren’t in here.  It may not see like much, but it adds up.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
object Euler001 {
  def main(args: Array[String]) {
    var a = 0
    var sum = 0
 
    while(a < 1000) {
      if(a%3 == 0 || a%5 == 0) sum = sum + a
 
      a = a + 1
    }
 
    println(sum)
  }
}

Using a while loop solved the problem.  I have more variations of the solution I will post later.  If you are trying to learn a new programming language, projects like Euler is a great way to do this.  For now just trust me, I will write a follow up article on why.

Be Sociable, Share!