Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Solution {
- /**
- * Calculates the sum of the first n natural numbers
- * with Time Complexity of O(1) and Space Complexity of O(1)
- * The constraint of n is assumed as 1 <= n < 65535
- * Any value over the upper bound will cause an overflow of the integer type of the result
- * @param n first N natural numbers
- * @return sum of first N natural numbers
- */
- public static int sumOfNaturalNumbers(int n) {
- return (int) ((long) n * ((long) (n + 1)) / 2);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement