Advertisement
amitsen01ei

SumOfNaturalNumbers.java

Jul 31st, 2023
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.51 KB | None | 0 0
  1. public class Solution {
  2. /**
  3. * Calculates the sum of the first n natural numbers
  4. * with Time Complexity of O(1) and Space Complexity of O(1)
  5. * The constraint of n is assumed as 1 <= n < 65535
  6. * Any value over the upper bound will cause an overflow of the integer type of the result
  7. * @param n first N natural numbers
  8. * @return sum of first N natural numbers
  9. */
  10. public static int sumOfNaturalNumbers(int n) {
  11. return (int) ((long) n * ((long) (n + 1)) / 2);
  12. }
  13. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement