find the sum of the multiples of 3 and 5 below 1000

前端 未结 12 965
我在风中等你
我在风中等你 2021-01-18 08:04

Ok guys, so I\'m doing the Project Euler challenges and I can\'t believe I\'m stuck on the first challenge. I really can\'t see why I\'m getting the wrong answer despite my

12条回答
  •  北恋
    北恋 (楼主)
    2021-01-18 09:01

    If you are using Java 8 you can do it in the following way:

    Integer sum = IntStream.range(1, 1000) // create range
                      .filter(i -> i % 3 == 0 || i % 5 == 0) // filter out
                      .sum(); // output: 233168
    

    To count the numbers which are divisible by both 3 and 5 twice you can either write the above line twice or .map() the 2 * i values:

    Integer sum = IntStream.range(1, 1000)
                      .filter(i -> i % 3 == 0 || i % 5 == 0)
                      .map(i -> i % 3 == 0 && i % 5 == 0 ? 2 * i : i)
                      .sum(); // output: 266333
    

提交回复
热议问题