Created
May 10, 2023 05:09
-
-
Save espinoco/67545f40b436c040ce0dd69e566e03c6 to your computer and use it in GitHub Desktop.
Sum the odd-square numbers less than a given integer n.
This file contains hidden or 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 Main { | |
public static void main(String[] args) { | |
assert oddSquareSum(1) == 0; | |
assert oddSquareSum(2) == 1; | |
assert oddSquareSum(9) == 1; | |
assert oddSquareSum(10) == 10; | |
assert oddSquareSum(44) == 35; | |
assert oddSquareSum(0) == 0; | |
assert oddSquareSum(7569) == 105995; | |
assert oddSquareSum(Integer.MAX_VALUE) == 16585052009610L; | |
} | |
// O(n) time & O(1) space - where n is the value of the integer input n | |
public static long oddSquareSum(int n) { | |
if (n < 0) { | |
throw new IllegalArgumentException(); | |
} | |
long sum = 0; | |
long oddNum = 1; | |
long oddSquareNum = 1; | |
while (oddSquareNum < n) { | |
sum += oddNum * oddNum; | |
oddNum += 2; | |
oddSquareNum = oddNum * oddNum; | |
} | |
return sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment