Get list of elements that are divisible by 3 or 5 from 1 - 1000

后端 未结 6 569
北海茫月
北海茫月 2021-01-14 12:30

I\'m trying to write a functional approach in scala to get a list of all numbers between 1 & 1000 that are divisible by 3 or 5

Here is what I have so far :

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 13:13

    The problem from projecteuler.net also wants a sum of those numbers at the end.

    "Find the sum of all the multiples of 3 or 5 below 1000."

    object prb1 {
      def main(args: Array[String]) {
        val retval = for{ a <- 1 to 999
                          if a % 3 == 0 || a % 5 == 0
        } yield a
        val sum = retval.reduceLeft[Int](_+_)
        println("The sum of all multiples of 3 and 5 below 1000 is " + sum)
      }
    }
    

    The correct answer should be 233168

提交回复
热议问题