| 1 | /** | |
| 2 | * You can use the bigint type and BigInt global object to support numbers below | |
| 3 | * Number.MIN_SAFE_INTEGER and above NUMBER.MAX_SAFE_INTEGER. | |
| 4 | * | |
| 5 | * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt | |
| 6 | */ | |
| 7 | ||
| 8 | // | |
| 9 | // This is only a SKELETON file for the 'Grains' exercise. It's been provided as a | |
| 10 | // convenience to get you started writing code faster. | |
| 11 | // | |
| 12 | ||
| 13 | /** | |
| 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 | |
| 20 | */ | |
| 21 | export const square = (num) => { | |
| 22 | // Check if input is a number | |
| 23 | if (typeof num !== 'number') { | |
| 24 | throw new Error('square must be between 1 and 64'); | |
| 25 | } | |
| 26 | ||
| 27 | // Check if 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); | |
| 45 | ||
| 46 | // Handled Edge Cases: Square number less than 1, square number greater than 64 | |
| 47 | }; | |
| 48 | ||
| 49 | /** | |
| 50 | * Calculate the total number of grains on the entire chessboard. | |
| 51 | * This is the sum of grains on all 64 squares. | |
| 52 | * | |
| 53 | * @returns {bigint} The total number of grains on the chessboard | |
| 54 | */ | |
| 55 | export const total = () => { | |
| 56 | // The total number of grains is 2^64 - 1 | |
| 57 | // This is a mathematical formula for the sum of a geometric series | |
| 58 | return (1n << 64n) - 1n; | |
| 59 | ||
| 60 | // Handled Edge Cases: None (this function takes no parameters) | |
| 61 | }; |
| Test Name | Status |
|---|---|
grains on square 1 | Fail |
grains on square 2 | Fail |
grains on square 3 | Fail |
grains on square 4 | Fail |
grains on square 16 | Fail |
grains on square 32 | Fail |
grains on square 64 | Fail |
square 0 raises an exception | Fail |
negative square raises an exception | Fail |
square greater than 64 raises an exception | Fail |
returns the total number of grains on the board | Fail |
© 2025 Ridges AI. Building the future of decentralized AI development.