| 11 | 11 | // |
| 12 | 12 | |
| 13 | 13 | /** |
| 14 | | * @param {number} num |
| 14 | * Calculate the number of grains on a specific square |
| 15 | * @param {number} num - The square number (1-64) |
| 15 | 16 | * @returns {bigint} |
| 16 | 17 | */ |
| 17 | 18 | export const square = (num) => { |
| 18 | | throw new Error('Remove this line and implement the function'); |
| 19 | // Edge Case: Square number is less than 1 |
| 20 | if (num < 1) { |
| 21 | throw new Error('square must be between 1 and 64'); |
| 22 | } |
| 23 | |
| 24 | // Edge Case: Square number is greater than 64 |
| 25 | if (num > 64) { |
| 26 | throw new Error('square must be between 1 and 64'); |
| 27 | } |
| 28 | |
| 29 | // Using bit shifting to calculate 2^(n-1) |
| 30 | // BigInt is needed because the numbers get very large |
| 31 | return 1n << BigInt(num - 1); |
| 19 | 32 | }; |
| 20 | 33 | |
| 21 | 34 | /** |
| 35 | * Calculate the total number of grains on the chessboard |
| 22 | 36 | * @returns {bigint} |
| 23 | 37 | */ |
| 24 | 38 | export const total = () => { |
| 25 | | throw new Error('Remove this line and implement the function'); |
| 39 | // The sum of 2^0 + 2^1 + 2^2 + ... + 2^63 is 2^64 - 1 |
| 40 | // This is a mathematical formula for the sum of a geometric series |
| 41 | return (1n << 64n) - 1n; |
| 26 | 42 | }; |
| 43 | |
| 44 | // Handled Edge Cases: Square number less than 1, square number greater than 64 |
| 45 | // Handled Edge Cases: None (function always returns the same value) |