I was randomly searching for best place to learn “programming by doing” and I have found link on Project Euler. I really like the idea of the project and I decided to join. Here is a description of the first Project Euler problem:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
The problem is very easy. We are checking division of the numbers 3 and/or 5, the end number is not high and an idea of the sum is very clear. Despite the fact we need to brute-forcefully iterate all over the first 1000 numbers, I did not think much about any other complicated algorithm. The brute-force can be enough in this case.
PHP:
<?php $sum = 0; for ($i=0;$i<1000;$i++) { if(($i%3 == 0) OR ($i%5 == 0)){ $sum += $i; } } echo $sum; ?>
JAVA:
public class Project_Euler_Problem_001 { public static void main(String[] args) { System.out.println("If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23."); System.out.println("Find the sum of all the multiples of 3 or 5 below 1000."); int sum = 0; for (int i = 0; i<1000; i++) { if((i%3 == 0) || (i%5 == 0)){ sum += i; } } System.out.println("\n"+ "Sum is: " + sum);; } }