| 11 | 11 | // |
| 12 | 12 | |
| 13 | 13 | /** |
| 14 | | * @param {number} num |
| 15 | | * @returns {bigint} |
| 14 | * Calculate the number of grains on a specific square of a chessboard. |
| 15 | * Each square has twice as many grains as the previous square. |
| 16 | * |
| 17 | * @param {number} num - The square number (1-64) |
| 18 | * @returns {bigint} The number of grains on that square |
| 19 | * @throws {Error} If the square number is not between 1 and 64 |
| 16 | 20 | */ |
| 17 | 21 | export const square = (num) => { |
| 18 | | throw new Error('Remove this line and implement the function'); |
| 22 | // Validate that input is a number |
| 23 | if (typeof num !== 'number') { |
| 24 | throw new Error('square must be between 1 and 64'); |
| 25 | } |
| 26 | |
| 27 | // Validate that input is an integer |
| 28 | if (!Number.isInteger(num)) { |
| 29 | throw new Error('square must be between 1 and 64'); |
| 30 | } |
| 31 | |
| 32 | // Edge Case: Square number is less than 1 |
| 33 | if (num < 1) { |
| 34 | throw new Error('square must be between 1 and 64'); |
| 35 | } |
| 36 | |
| 37 | // Edge Case: Square number is greater than 64 |
| 38 | if (num > 64) { |
| 39 | throw new Error('square must be between 1 and 64'); |
| 40 | } |
| 41 | |
| 42 | // Calculate grains on square using bit shift for efficiency |
| 43 | // Square n has 2^(n-1) grains |
| 44 | return 1n << BigInt(num - 1); |
| 19 | 45 | }; |
| 20 | 46 | |
| 21 | 47 | /** |
| 22 | | * @returns {bigint} |
| 48 | * Calculate the total number of grains on the entire chessboard. |
| 49 | * This is the sum of grains on all 64 squares. |
| 50 | * |
| 51 | * @returns {bigint} The total number of grains on the chessboard |
| 23 | 52 | */ |
| 24 | 53 | export const total = () => { |
| 25 | | throw new Error('Remove this line and implement the function'); |
| 54 | // The total number of grains is 2^64 - 1 |
| 55 | // This is a mathematical formula for the sum of a geometric series |
| 56 | return (1n << 64n) - 1n; |
| 26 | 57 | }; |
| 58 | |
| 59 | // Handled Edge Cases: |
| 60 | // - Square number less than 1 in square function |
| 61 | // - Square number greater than 64 in square function |