Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save croespino/67545f40b436c040ce0dd69e566e03c6 to your computer and use it in GitHub Desktop.
Save croespino/67545f40b436c040ce0dd69e566e03c6 to your computer and use it in GitHub Desktop.
Sum the odd-square numbers less than a given integer n.
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