Project Euler – Problem 1 Solution (Take 2) (Java)
http://projecteuler.net/index.php?section=problems&id=1
I mentioned Project Euler to some of my co-workers and one of them, Daniel, is hooked. He came up with a better solution for Problem 1 than I had, but it was still an O(n) algorithm. We talked about it a little and our discussion lead to this constant time solution. Yay for teamwork!
/* Project Euler - Problem 1 (http://projecteuler.net/index.php?section=problems&id=1)
*
* Using basic summations, get the sums of all multiples of 3, 5 and 3*5. Add the
* summations for 3 and 5, then subtract the summation for 15.
*/
public static void p1(){
double a = 3, b = 5, n = 999;
double sum;
sum = (a*summation(Math.floor(n/a))) + (b*summation(Math.floor(n/b))) - (a*b*summation(Math.floor(n/(a*b))));
System.out.println((int)sum);
}
/* Basic summation function. Returns the sum from 1 to n */
public static double summation(double n){
return n*(n+1)/2;
}
Tina on January 31st 2009 in Project Euler