Project Euler Problem 1

Project Euler Problem 1

The following is my solution to the first Project Euler problem. Project Euler is a large list of programming problems of varying complexities with an emphasis on mathematics.

The problem is as follows:

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.

Java code:

package projecteuler1;
import java.util.HashSet;

/**
 *
 * @author Eynar Roshev
 */
public class ProjectEuler1 {
    public static void main(String[] args) {
        ProjectEuler1 pe1 = new ProjectEuler1();
        HashSet<Integer> m3 = pe1.multiples(3, 1000);
        HashSet<Integer> m5 = pe1.multiples(5, 1000);
        HashSet<Integer> m3m5 = new HashSet<Integer>(m3);
        m3m5.addAll(m5);
        int sum = 0;
        for (Integer i: m3m5) {
            sum += i;
        }
        System.out.println(sum);
        
    }

    HashSet<Integer> multiples(int n, int range) {
        HashSet<Integer> list = new HashSet<Integer>();
        int increment = 1;
        int multiple = n * increment;
        while (multiple < range) {
            list.add(multiple++);
            increment++;
            multiple = n * increment;
        }
        return list;
    }
}

(Source)

We define a function to calculate the multiples of \(n\) in a given range and apply it for \(n \in \{3, 5\}\) which gives us two sets m3 and m5, containing the multiples of 3 and 5 respectively. We use sets because there may be overlapping multiples between both collections – which we do not want.

m3m5 is the union of m3 and m5, and we calculate the sum of the values of this set.

Leave a Reply

Your email address will not be published. Required fields are marked *