Skip to content

Instantly share code, notes, and snippets.

@dxu
Created February 12, 2012 09:26
Show Gist options
  • Save dxu/1807475 to your computer and use it in GitHub Desktop.
Save dxu/1807475 to your computer and use it in GitHub Desktop.
Program for Sum of Multiples
public class SumOfMultiples {
public static int sumOfMultiples(int first, int second, int high){
//use summation
int ceiling = high-1;
//need to subtract the overlapping elements
int product = first * second;
//find the biggest multiple less than 1000
int first_multiple = ceiling / first;
int second_multiple = ceiling / second;
int product_multiple = ceiling / product;
//summation of each
int f_sum = first * (first_multiple * (first_multiple+1))/2;
int s_sum = second * (second_multiple * (second_multiple+1))/2;
int p_sum = product * (product_multiple * (product_multiple+1))/2;
//subtract overlapping elements
return f_sum + s_sum - p_sum;
}
public static void main(String[] args){
int solution = sumOfMultiples(3,5,1000);
System.out.println(solution);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment