Problem 48

Run Settings
LanguageJavaScript
Language Version
Run Command
/* * Function multiplies a multiple-digit number (array of digits) by a fixed number, * while a applying a shift (this is a base operation in the standard multiplocation * algorithm) * Additionally, there is a truncation of the result to a certain number of digits */ function truncatedMultiplyByNumber(array, number, shift, truncationThreshold) { const newArray = []; let uebertrag = 0; for (let nullindex = 0; nullindex < shift; nullindex++) { if (nullindex >= truncationThreshold) { return newArray } newArray.push(0) } for (let index = 0; index < array.length; index++) { if (index + shift >= truncationThreshold) {uebertrag = 0; break} const wert = (uebertrag + array[index] * number) newArray.push(wert % 10); uebertrag = (wert - (wert % 10)) / 10; } while (uebertrag > 0) { newArray.push(uebertrag % 10); uebertrag = (uebertrag - (uebertrag % 10)) / 10; } return newArray; } /* * Function inmplements a summation while truncating the result to a certain * number of digits */ function truncatedAddition(array1, array2, truncationThreshold) { const resultArray = []; let i = 0; uebertrag = 0; while (array1[i] != undefined || array2[i] != undefined || uebertrag > 0) { if (i >= truncationThreshold) {break} const value = (array1[i] || 0) + (array2[i] || 0) + uebertrag; resultArray.push(value % 10); uebertrag = (value - value % 10) / 10 i += 1; } return resultArray; } /* * Function implements the full multiplication of two multi-digit numbers (arrays) * while truncating all the steps in the algorithm to be performed with truncated * numbers */ function truncatedMultiplication(array1, array2, truncationThreshold) { let result = [0] array1.forEach((x, index) => { result = truncatedAddition(result, truncatedMultiplyByNumber(array2, x, index, truncationThreshold), truncationThreshold)}) return result; } /* * Function implements a truncated version of the power function. All calculations * are essentially carried out with numbers truncated to a certain number of digits */ function truncatedSelfPower(number, truncationThreshold,) { const numberArr = number.toString().split('').map(x => parseInt(x)).reverse() let resultArr = [...numberArr]; for (let i = 1; i < number; i++) { resultArr = truncatedMultiplication(numberArr, resultArr, truncationThreshold ) } return resultArr } function calculateSelfPowerSum(number, truncationThreshold) { result = [0]; for (let i= 1; i <= number; i++) { result = truncatedAddition(result, truncatedSelfPower(i, truncationThreshold), truncationThreshold) } return result } console.log(calculateSelfPowerSum(1000, 10).reduce((a,b,index) => a + b * 10 ** (index)))
Editor Settings
Theme
Key bindings
Full width
Lines