|
| 1 | +/* |
| 2 | + * Fermat's Last Theorem states: |
| 3 | + * |
| 4 | + * For every integer n >= 3, the equation |
| 5 | + * |
| 6 | + * x^n + y^n = z^n |
| 7 | + * |
| 8 | + * has no nontrivial integer solutions (x, y, z > 0). |
| 9 | + * |
| 10 | + * In contrast, for n = 2 there are infinitely many solutions (the famous |
| 11 | + * Pythagorean triples like 3^2 + 4^2 = 5^2). |
| 12 | + * |
| 13 | + * While Andrew Wiles proved this theorem in 1994 using advanced mathematics |
| 14 | + * (elliptic curves and modular forms), we can illustrate the theorem in JavaScript |
| 15 | + * by brute-force checking ranges of x, y, z for small exponents n. |
| 16 | + * |
| 17 | + * within checked ranges, no counterexamples exist for n >= 3. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * Check for counterexamples to Fermat's Last Theorem within a bounded range. |
| 22 | + * |
| 23 | + * This function uses BigInt arithmetic to handle large ranges safely. |
| 24 | + * |
| 25 | + * @param {number} maxValue - The maximum integer to check for x and y |
| 26 | + * @param {number} exponent - The power n (>= 3) |
| 27 | + * @returns {Array} - Array of counterexamples found (should be empty) |
| 28 | + */ |
| 29 | + |
| 30 | +const checkFermatLastTheorem = (maxValue, exponent) => { |
| 31 | + if (exponent < 3) { |
| 32 | + throw new Error("Fermat's Last Theorem only applies for n >= 3") |
| 33 | + } |
| 34 | + |
| 35 | + const counterexamples = [] |
| 36 | + const exponentBigInt = BigInt(exponent) |
| 37 | + |
| 38 | + for (let baseX = 1; baseX <= maxValue; baseX++) { |
| 39 | + const baseXPowerN = BigInt(baseX) ** exponentBigInt |
| 40 | + |
| 41 | + for (let baseY = baseX; baseY <= maxValue; baseY++) { |
| 42 | + const baseYPowerN = BigInt(baseY) ** exponentBigInt |
| 43 | + const sumOfPowers = baseXPowerN + baseYPowerN |
| 44 | + |
| 45 | + // compute integer nth root of sumOfPowers using binary search |
| 46 | + let lowerBound = 1n |
| 47 | + let upperBound = sumOfPowers |
| 48 | + let potentialZ = 0n |
| 49 | + |
| 50 | + while (lowerBound <= upperBound) { |
| 51 | + const middle = (lowerBound + upperBound) >> 1n |
| 52 | + const middlePowerN = middle ** exponentBigInt |
| 53 | + |
| 54 | + if (middlePowerN === sumOfPowers) { |
| 55 | + potentialZ = middle |
| 56 | + break |
| 57 | + } else if (middlePowerN < sumOfPowers) { |
| 58 | + lowerBound = middle + 1n |
| 59 | + } else { |
| 60 | + upperBound = middle - 1n |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + // exact check |
| 65 | + if (potentialZ > 0n && potentialZ ** exponentBigInt === sumOfPowers) { |
| 66 | + counterexamples.push({ |
| 67 | + x: baseX, |
| 68 | + y: baseY, |
| 69 | + z: potentialZ.toString(), |
| 70 | + n: exponent |
| 71 | + }) |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + return counterexamples |
| 77 | +} |
| 78 | + |
| 79 | +export default checkFermatLastTheorem |
0 commit comments