Created
January 18, 2016 04:21
-
-
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
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 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