Project Euler – Problem 1 Solution (Java)
http://projecteuler.net/index.php?section=problems&id=1
/* Project Euler - Problem 1 (http://projecteuler.net/index.php?section=problems&id=1)
*
* This problem is pretty straightforward, however, rather than going the brute-force
* route and checking each number from 1 to 999 to see if 3 or 5 is a divsor,
* I realized that I can break the numbers up in to groups of 15 (3*5) and find a
* pattern within the group. It is still an O(n) runtime, but with some tweaking I should be able
* to get rid of the inner loop.
*/
public static void p1(){
int n = 0;
int sum = 0;
int nums[] = {3, 2, 1, 3, 1, 2, 3}; /* Distances between 3, 5, 6, 9, 10, 12, 15 */
do {
for(int i=0;i<nums.length;i++){
n=n+nums[i];
if(n<1000) sum=sum+n;
else break;
}
} while(n<1000);
System.out.println(sum);
}
Tina on January 28th 2009 in Project Euler