Skip to content

Instantly share code, notes, and snippets.

@jluismm2311
Created December 2, 2015 19:08
Show Gist options
  • Save jluismm2311/aefbbd3ae8297640a3e9 to your computer and use it in GitHub Desktop.
Save jluismm2311/aefbbd3ae8297640a3e9 to your computer and use it in GitHub Desktop.
Sum of 'n' Numbers sum_of_n (or SequenceSum.sumOfN in Java, SequenceSum.SumOfN in C#) takes an integer n and returns a List (an Array in Java/C#) of length abs(n) + 1. The List/Array contains the numbers in the arithmetic series produced by taking the sum of the consecutive integer numbers from 0 to n inclusive. n can also be 0 or a negative val…
public class SequenceSum {
public static int[] sumOfN(int n) {
boolean isNegative = n < 0;
int arraySize = Math.abs(n)+1;
int[] result= new int[arraySize];
for(int i = 1; i < arraySize;i++){
result[i] = isNegative? result[i-1] - i: result[i-1] + i;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment