From charlesreid1

(Created page with "==Question== 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 multip...")
 
No edit summary
Line 8: Line 8:


Two-part problem: enumerating multiples of 3 or 5, and summing them up.
Two-part problem: enumerating multiples of 3 or 5, and summing them up.
Data structure:
* Use a set to store integers and avoid duplicates.


Task 1: generate all multiples of b, up to a given maximum N.
Task 1: generate all multiples of b, up to a given maximum N.
Line 13: Line 16:
* Generate numbers from 1 to N/b.
* Generate numbers from 1 to N/b.
* Multiply them by b to generate numbers up to N that are multiples.
* Multiply them by b to generate numbers up to N that are multiples.
* Use a set to keep all the numbers.


Task 2: sum them up.
Task 2: sum them up.
* Iterate over your set using a generator.
* Iterate over your set using a generator.


==Code==
<pre>
import java.util.Set;
import java.util.HashSet;
public class Euler {
public static void main(String[] args) {
// Maximum
int max = 100;
// Multiples list
int[] multiplesList = {3,5};
// Results set
Set<Integer> s = new HashSet<Integer>();
// From 1 up to and including (max-1)/multiple (not max/multiple-1)
for(int m=0; m<multiplesList.length; m++) {
int multiple = multiplesList[m];
for(int i=1; i<=((max-1)/multiple); i++) {
int num = i*multiple;
s.add(num);
}
}
// Sum them all up
int sum = 0;
for(Integer i : s) {
sum += i;
}
System.out.println("sum = "+sum);
}
}
</pre>





Revision as of 21:02, 13 June 2017

Question

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.

Approach

Two-part problem: enumerating multiples of 3 or 5, and summing them up.

Data structure:

  • Use a set to store integers and avoid duplicates.

Task 1: generate all multiples of b, up to a given maximum N.

  • Given a maximum N, biggest number t hat can be a multiple of b is N/b.
  • Generate numbers from 1 to N/b.
  • Multiply them by b to generate numbers up to N that are multiples.

Task 2: sum them up.

  • Iterate over your set using a generator.

Code

import java.util.Set;
import java.util.HashSet;

public class Euler {
	public static void main(String[] args) { 
		// Maximum
		int max = 100;
		
		// Multiples list
		int[] multiplesList = {3,5};
		
		// Results set
		Set<Integer> s = new HashSet<Integer>();

		// From 1 up to and including (max-1)/multiple (not max/multiple-1)
		for(int m=0; m<multiplesList.length; m++) { 
			int multiple = multiplesList[m];
			for(int i=1; i<=((max-1)/multiple); i++) { 
				int num = i*multiple;
				s.add(num);
			}
		}
		
		// Sum them all up
		int sum = 0;
		for(Integer i : s) { 
			sum += i;
		}
		System.out.println("sum = "+sum);
	}

}