diff --git a/2022/03/algorithms/factorial2.js b/2022/03/algorithms/factorial2.js new file mode 100644 index 0000000..5b5e377 --- /dev/null +++ b/2022/03/algorithms/factorial2.js @@ -0,0 +1,119 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', function(inputStdin) { + inputString += inputStdin; +}); + +process.stdin.on('end', function() { + inputString = inputString.split('\n'); + + main(); +}); + +process.on('SIGINT', function() { + inputString = inputString.split('\n'); + + main(); + process.exit(0); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/* + * Complete the 'extraLongFactorials' function below. + * + * The function accepts INTEGER n as parameter. + */ + +// the idea to store digits in array +// but the system is 1000 base instead of 10 +// just for printing issues + +function convert_to(n) { + let res = []; + let digit; + do { + digit = n % 1000; + res.unshift(digit); + n = Math.floor(n / 1000); + } while (n > 0); + + return res; +} + +function sum(a, b) { + let da, db, shift = 0, res; + let digits = []; + while (a.length || b.length) { + da = a.length ? a.pop() : 0; + db = b.length ? b.pop() : 0; + res = da + db + shift; + digits.unshift(res % 1000); + shift = Math.floor(res / 1000); + } + if (shift > 0) { + digits.unshift(shift); + } + return digits; +} + +function multiply(a, b) { + // console.log('multiply', a, b); + let n = a.length; + let m = b.length; + let da, db, shift = 0, res; + + let offsetArray = []; + let subSum; + let sumAll = [0]; + + for (let i = m - 1; i >= 0; i--) { + subSum = [...offsetArray]; + offsetArray.push(0); + for (let j = n - 1; j >= 0; j--) { + res = b[i] * a[j] + shift; + subSum.unshift(res % 1000); + shift = Math.floor(res / 1000); + } + if (shift > 0) { + subSum.unshift(shift); + } + // console.log('Subsum', subSum); + sumAll = sum(sumAll, subSum); + // console.log('Summed', sumAll); + } + return sumAll; +} + +function extraLongFactorials(n) { + let m = [1]; + let factor = [0]; + for (let i = 0; i < n; i++) { + factor = sum(factor, [1]); + console.log(`Factor`, m, factor); + m = multiply(m, factor); + } + + console.log(`Result`, m); + + let s = "" + m[0]; + for (let i = 1; i < m.length; i++) { + s += ("" + m[i]).padStart(3, "0"); + } + + console.log(s); +} + +function main() { + const n = parseInt(readLine().trim(), 10); + + extraLongFactorials(n); +}