Created
February 12, 2012 09:26
-
-
Save dxu/1807475 to your computer and use it in GitHub Desktop.
Program for Sum of Multiples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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