Skip to content

Instantly share code, notes, and snippets.

@deyindra
Created January 18, 2016 04:21
Show Gist options
  • Save deyindra/405fcb11369baa35924d to your computer and use it in GitHub Desktop.
Save deyindra/405fcb11369baa35924d to your computer and use it in GitHub Desktop.
Given a number n where n>0 calculate sum of all number which are divisible by 3 or 5 between 1 to n
public static long calculateAP(long start, long totalNumber, long difference){
return (totalNumber*((2*start)+(totalNumber-1)*difference))/2;
}
//Time complexity O(1) and Space complexity O(1)
public static long sumOfDivisbleOf30r5(int number){
long totalNumberDivisibleby3=number/3;
long totalNumberDivisibleby5 = number/5;
long totalNumberDivisibleby15 = number/(3*5);
return calculateAP(3,totalNumberDivisibleby3,3)
+calculateAP(5,totalNumberDivisibleby5,5)
-calculateAP(15,totalNumberDivisibleby15,15);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment