I'm trying to find all of the numbers that are multiple of 3 or 5 below 1000. After I get all of the numbers, I would like to add them up.
I was able to figure out how to find the multiples and add them to an array but unable to figure out how to add them together.
Here's my code:
var add = [];
var count = 0;
if ( i % 3 == 0 || i %5 == 0) {
for (var i = 1; i <= 1000; i ++) {
add.push(i);
}
};
function whole () {
for(var i = 0 ; i <= add.length; i ++) {
count = count + add[i];
}
};
whole();
The first loop won't ever happen because i is undefined (i%3 is NaN) at that point.
I think you just need to invert the for with the if.
for (var i = 1; i <= 1000; i ++) {
if ( i % 3 == 0 || i %5 == 0) {
add.push(i);
}
};
The assertion that you need to return count isn't true. The function is simply going to act on the global count.
A cleaner, functionally pure way to do this:
function whole(i, count, max){
if(i > max){
return count;
}
if(i % 3 === 0 || i % 5 === 0){
return whole(i + 1, count + i, max);
}
return whole(i + 1, count, max);
}
whole(0, 0, 1000);
You need to put the condition inside the loop as well letting the loop run until i < 1000 because you only want the numbers below 1000.
for (var i = 1; i < 1000; i ++) {
if (i % 3 == 0 || i %5 == 0) {
add.push(i);
}
}
In the whole function you need to run ntil i < add.lengthor else you will try to add an undefined index to your sum.
function whole () {
for(var i = 0 ; i < add.length; i ++) {
count = count + add[i];
}
};
I think that you were close. In your whole function, you need to return count.
function whole () {
for(var i = 0 ; i <= add.length; i ++) {
count = count + add[i];
}
return count;
};
Here's a better way to sum an array of numbers.
You can use a reduce function on your array to get a "reduced" value
add.reduce(function(x,y) { return x+y; }, 0);
For example ((0 + 1) + 2) + 3 will return 6
[1,2,3].reduce(function(x,y) { return x+y; }, 0); //=> 6
Here's another interesting way to potentially solve the problem with a more functional approach.
It uses ES6, but do not fret. You can easily copy/paste the example into babeljs.io/repl to see it run. Babel will also give you the equivalent ES5.
// let's say we have an array of 1000 numbers
let ns = new Array(1000);
// fill the array with numbers
for (let i=0, len=ns.length; i<len; i++) {
ns[i] = i+1;
}
// some reusable functions
let mod = y => x => x % y;
let eq = y => x => x === y;
let id = x => x;
let filter = f => xs => xs.filter(f);
let reduce = f => i => xs => xs.reduce(uncurry(f), i);
let comp = g => f => x => g(f(x));
let compN = reduce(comp)(id);
let uncurry = f => (x,y) => f(x)(y);
// these are some helpers you could define using the reusable functions
let add = y => x => x + y;
let sum = reduce(add)(0);
let divisibleBy = x => comp(eq(0))(mod(x));
// define your solution as a composition
// of `sum`, `divisbleBy(5)`, and `divisibleBy(3)`
let solution = compN([
sum,
filter(divisibleBy(5)),
filter(divisibleBy(3))
]);
// output the solution passing in the original `ns` array
console.log(solution(ns));
Just call reduce without start parameter.
arr.reduce(callback[, initialValue]): If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second. MDN
add.reduce(function(x, y) { return x + y; });
Related
My question maybe seems like duplicated but I can't find how to do this in vanilla javascript.
(I found answer in python here.)
So basically I want to get a list of all possible combinations of number that sum up to a desired number.
For example:
function sum_to_n(n,size){}
x = sum_to_n(6,3)
// [6,0,0] [5,1,0] [4,2,0] [4,1,1] [3,3,0] [3,2,1] [2,2,2]
This is what I can do so far:
function sum_to_n(n, size, sum=[], limit) {
if (size === 1) {
sum.push(n)
return sum
}
if (!limit) {
limit = n
}
let start = Math.min(n, limit)
let stop = Math.ceil(n/size) - 1
for (let i = start; i > stop; i--) {
let tmp = [...sum];
tmp.push(i)
let combination = sum_to_n(n-i, size - 1, tmp, i)
if (combination) {
console.log(combination) // this work
}
}
}
// I don't know how to make this work
let x = sum_to_n(6, 3)
// or maybe this
for (let y in sum_to_n(6,3)) {
console.log(y)
}
This is closely related to partitions of an integer, which finds all distinct ways of breaking an integer into the sum of positive integers. For instance, the partitions of 4 are 4, 3 + 1, 2 + 2, 2 + 1 + 1, and 1 + 1 + 1 + 1. Although there is probably a more direct way of calculating your sum, it's easy to do atop a partitions function:
const partitions = (n, max = n) =>
n == 0
? [[]]
: n < 0
? []
: Array .from ({length: Math .min (n, max)}, (_, i) => i + 1) // or use a `ramge` function
.reverse()
.flatMap (x => partitions (n - x, x) .map (p => [x, ...p]))
const sumToN = (n, c) =>
partitions (n + c)
.filter (p => p .length == c)
.map (p => p .map (x => x - 1))
console .log (sumToN (6, 3))
.as-console-wrapper {max-height: 100% !important; top: 0}
(The reverse call is not strictly necessary, but the usual partition description is written in this order, as is your requested output. The Array.from (...) call would be better expressed using a range function, but is not horrible inlined like this.)
We need to do two things: we have to find only those of the correct length, and we need to allow zeros as well as the positive numbers that partition generates. We can do this by partitioning a larger number and subtracting 1 from each value in every partition, and filtering the results down to those with the proper length.
The larger number we need -- since we're going to subtract 1 for every one of our c elements in each partition -- is simply n + c.
This algorithm's performance is exponential in n. But that's necessary as there are an exponential number of such partitions, and presumably an exponential number of results for your requested output. (I don't know a proof of this, and it's possible I'm wrong. If I am, I'd love to see a sub-exponential algorithm.)
'use strict';
function _sumToN(n, size, acc = [], solutions = []) {
if (size === 0) {
const sum = acc.reduce((sum, num) => sum + num);
return sum === n ? solutions.concat([acc]) : solutions;
}
for (let i = 0; i <= n; ++i)
solutions = _sumToN(n, size - 1, acc.concat(i), solutions);
return solutions;
}
function sumToN(n, size) {
return _sumToN(n, size);
}
console.log(sumToN(6, 3));
The above uses a driver, _sumToN, which accepts an additional acc accumulator array, and a solutions array that will eventually hold all the solutions. It iterates as follows:
0 0 0
0 0 1
0 0 2
...
0 0 6
...
6 6 6
and saves off solutions when they sum to n. There are of course optimizations that can be made, but hopefully this trivial implementation helps.
let sum_to_n = (n, iteration_limit) => {
let res = [];
for (let i = 0; i < iteration_limit; i++) {
for (let j = 0; j < iteration_limit; j++) {
for (let h = 0; h < iteration_limit; h++) {
if(i+j+h == n){
res.push([i, j, h])
}
}
}
}
return res;
};
This worked for me, however it does not have a size parameter.
let getOperator = (size, arr, expect) => {
let ev = "";
for (let i = 0; i < size; i++) {
ev += `${arr[i]}+`;
}
return `${ev.slice(0, ev.length-1)} == ${expect}`;
}
let sum_to_n = (n, size, iteration_limit) => {
return new Promise(resolve => {
let identifiers = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split('');
let all_identifiers = [];
let res = [];
let ev = "";
for (let i = 0; i < size; i++) {
let r = identifiers[i];
all_identifiers.push(r);
ev += `for (let ${r} = 0; ${r} < iteration_limit; ${r}++){\n`;
}
let push_value_string = "";
for (let i = 0; i < all_identifiers.length; i++) {
push_value_string += `${all_identifiers[i]}, `;
}
ev += `\nif(${getOperator(size, all_identifiers, n)}){\nres.push([${push_value_string.slice(0, push_value_string.length-1)}]);\n}`;
for (let i = 0; i < size; i++) {
ev += "}";
}
console.log(ev);
eval(ev);
resolve(res);
});
};
sum_to_n(15, 3, 100).then(console.log);
Basically depending on the size it will make a JavaScript code in a text size times, save what word it used for the for loop and check if the addition of all is equal to n. Then evaluate it and resolve it.
I need to build a function that returns a given number shuffled writing one digit from the front of the number and the following taken from the back, then the 3rd digit from the front of the number and the 4th from the back and so on.
Example:
const initialNumber = 123456 should return
const finalNumber = 162534
or
const initialNumber2 = 104 should return
const finalNumber2 = 140
Also, the number should be between the values of 0 and 100.000.000.
How to do it? Should I first transform the number into an array first of all using the split() method and then using a for loop?
You can do it with splitting the input into array and reduce:
const shuffle = input => input.toString().split('').reduce((acc, item, index, data) => {
const arr = (index % 2 ? data.slice().reverse() : data);
return acc.concat(arr[Math.floor(index / 2)]);
}, []).join('');
console.log(shuffle(104)); // 140
console.log(shuffle(123456)); // 162534
console.log(shuffle(1234567)); // 1726354
A bit reduced code:
const shuffle = input => input.toString().split('').reduce((acc, item, index, data) =>
acc.concat((index % 2 ? data.slice().reverse() : data)[Math.floor(index / 2)]), []
).join('');
I would prefer converting the number to a string, then using that string in a for loop.
function shuffle(num) {
var str = num.toString();
var result = "";
if(!isNaN(num) && num >= 0 && num <= 100000000) {
for(var i = 0; i < str.length; i++) {
if(i % 2 == 0) {
result += str[Math.floor(i / 2)];
} else {
result += str[str.length - Math.floor(i / 2 + 1)];
}
}
}
return result;
}
console.log(shuffle(123456)); // 162534
console.log(shuffle(1234567)); // 1726354
console.log(shuffle(104)); // 140
This may work as a very basic algo.
function shuffleNum(num,i){
var numArr = num.toString().split('');
var front = numArr.splice(0,i);
var back = numArr.pop();
var shuffledArr = front.concat(back,numArr);
return parseFloat(shuffledArr.join(''));
}
// Test
var num = 12345;
for(var i=0;i<num.toString().length;i++){
num = shuffleNum(num);
console.log(num);
}
// Output
// 51234
// 45123
// 34512
// 23451
// 12345
The best way is to use array push function.
function shuffle(a) {
var b = a.toString();
var c = [];
for(let i=0; i<b.length/2; i++) {
c.push(b[i]);
if(i==(Math.ceil(b.length/2)-1) && b.length%2==1) continue;
c.push(b[b.length-i-1]);
}
return c.join("");
}
Java code snippet.
public static int solution(int a) {
int[] arr = Integer.toString(a).chars().map(e->e-'0').toArray();
System.out.println(Arrays.toString(arr));
int[] temp = new int[arr.length];
int j=1;
for(int i = 0; i<arr.length; i++) {
if(i % 2 == 0) {
temp[i] = arr[i/2];
} else {
temp[i] = arr[arr.length - j];
j++;
}
}
System.out.println(Arrays.toString(temp));
I need help... I'm learning JavaScript, and it seems easy, but I may just be overlooking... everything... My problem is I need to return a string of all the even numbers between 0 and num inclusive; ex 7 gets you 0246, etc. I've gotten:
function stringOfEvens(num) {
for (let i = 0; i <= num.length; ++i) {
if (i % 2 === 0 ); {
return i;
}
}
}
I know the whole outlook is to run a for loop that goes from 0 to the number in question appending each time and if that number % 2 = 0, return that number, but something is a miss... I may even be overthinking and approaching this whole thing wrong... It is figuratively driving me mad...
function theJob(limit) {
var res = ''; //initialize as a string so that the other numbers will be appended instead of added
for (i = 0; i <= limit; i += 2) { // step increase by 2 to skip odd numbers
res += i;
}
return res; // returning the resulting string
}
console.log(theJob(10));
You can do this without using the modular function, by simply starting the loop at zero and incrementing by 2 each time the loop iterates...
function stringOfEvens(num) {
var result = "";
for (let i = 0; i <= num; i += 2) {
result += i; // append this even number to the result string
}
return result;
}
console.log(stringOfEvens(10));
You're returning the first number you find. a better approach would be to build the string in the loop then return after that string after the loop. Also no need for num.length if num is an int.
function stringOfEvens(num) {
var stringToReturn = "";
for (let i = 0; i <= num; i++) {
if (i % 2 === 0) {
stringToReturn = stringToReturn + i;
}
}
return stringToReturn;
}
function stringOfEvens(num) {
var str= ' ';
for(var i = 0; i <= num; i = i + 2){
str += i;
}
return str;
}
console.log(stringOfEvens(10))
Just for fun, since it's not particularly efficient:
const stringOfEvens = n => Array(~~(n/2)+1).fill().map((_, i) => 2*i).join("")
or annotated:
const stringOfEvens = n => // arrow function definition, returning:
Array(~~(n / 2) +1) // a sparse array of the required length
.fill() // made unsparse, so .map works
.map((_, i) => 2 * i) // then containing the even numbers
.join("") // and converted to a string
or alternatively (and more efficiently) using Array.from which can call an explicit map function in place:
const stringOfEvens = n => Array.from(Array(~~(n/2)+1), (_, i) => 2*i).join("")
I'm trying to solve this exercise. There is a string of numbers and among the given numbers the program finds one that is different in evenness, and returns a position of this number. The element has to be returned by its index (with the number being the actual position the number is in). If its index 0, it has to be returned as 1. I have this so far but it's not passing one test. I'm not too sure why because it feels like it should. Is anyone able to see what the error is? Any help is appreciated!
function iqTest(numbers) {
var num = numbers.split(" ");
var odd = 0;
var even = 0;
var position = 0;
for(var i = 0; i < num.length; i++) {
if(num[i]%2!==0) {
odd++;
if(odd===1) {
position = num.indexOf(num[i]) + 1;
}
}
else if(num[i]%2===0) {
even++;
if(even===1) {
position = num.indexOf(num[i]) + 1;
}
}
}
return position;
}
iqTest("2 4 7 8 10") output 3
iqTest("2 1 2 2") output 2
iqTest("1 2 2") outputs 2 when it should be 1
The simplest way is to collect all even/odd positions in subarrays and check what array has the length 1 at the end:
function iqTest(numbers) {
numbers = numbers.split(' ');
var positions = [[], []];
for (var i = 0; i < numbers.length; i++) {
positions[numbers[i] % 2].push(i + 1);
}
if(positions[0].length === 1) return positions[0][0];
if(positions[1].length === 1) return positions[1][0];
return 0;
}
console.log(iqTest("2 4 7 8 10"))
console.log(iqTest("2 1 2 2"))
console.log(iqTest("1 2 2"))
console.log(iqTest("1 3 2 2"))
Your code is overly complex.
Since the first number determines whether you're looking for an even number or an odd one, calculate it separately. Then, find the first number that doesn't match it.
function iqTest(numbers) {
numbers = numbers.split(" ");
var parity = numbers.shift() % 2;
for( var i=0; i<numbers.length; i++) {
if( numbers[i] % 2 != parity) {
return i+2; // 1-based, but we've also skipped the first
}
}
return 0; // no number broke the pattern
}
That being said, iqTest("1 2 2") should return 2 because the number in position 2 (the first 2 in the string) is indeed the first number that breaks the parity pattern (which 1 has established to be odd)
You have to define which "evenness" is the different one. Use different counters for the two cases, and return -1 if you don't have a single different one. Something like this:
function iqTest(numbers) {
var num = numbers.split(" ");
var odd = 0;
var even = 0;
var positionOdd = 0;
var positionEven = 0;
for(var i = 0; i < num.length; i++) {
if(num[i]%2!==0) {
odd++;
if(odd===1) {
positionOdd = i + 1;
}
}
else if(num[i]%2===0) {
even++;
if(even===1) {
positionEven = i + 1;
}
}
}
if (odd == 1)
return positionOdd;
else if (even == 1)
return positionEven;
else
return -1;
}
Note that, if you have exactly a single even number and a single odd one, the latter will be returned with the method of mine. Adjust the logic as your will starting from my solution.
Since the first number determines whether you're looking for an even number or an odd one, calculate it separately.
Then, find the first number that doesn't match it.
function iqTest(numbers){
// ...
const numArr = numbers.split(' ');
const checkStatus = num => (parseInt(num) % 2) ? 'odd' : 'even';
const findUniqueStatus = array => {
let numEvens = 0;
array.forEach(function(value){
if (checkStatus(value) == 'even') { numEvens++; }
});
return (numEvens === 1) ? 'even' : 'odd'
}
let statuses = numArr.map(checkStatus),
uniqueStatus = findUniqueStatus(numArr);
return statuses.indexOf(uniqueStatus) + 1;
}
}
public static int Test(string numbers)
{
var ints = numbers.Split(' ');
var data = ints.Select(int.Parse).ToList();
var unique = data.GroupBy(n => n % 2).OrderBy(c =>
c.Count()).First().First();
return data.FindIndex(c => c == unique) + 1;
}
I am just starting JS, and understand the concept of finding a factor. However, this snippet of code is what I have so far. I have the str variable that outputs nothing but the first factor which is 2. I am trying to add each (int) to the str as a list of factors. What's the wrong in below code snippet?
function calculate(num) {
var str = "";
var int = 2;
if (num % int == 0) {
str = str + int;
int++;
} else {
int++;
}
alert(str);
}
calculate(232);
UPDATED ES6 version:
As #gengns suggested in the comments a simpler way to generate the array would be to use the spread operator and the keys method:
const factors = number => [...Array(number + 1).keys()].filter(i=>number % i === 0);
console.log(factors(36)); // [1, 2, 3, 4, 6, 9, 12, 18, 36]
ES6 version:
const factors = number => Array
.from(Array(number + 1), (_, i) => i)
.filter(i => number % i === 0)
console.log(factors(36)); // [1, 2, 3, 4, 6, 9, 12, 18, 36]
https://jsfiddle.net/1bkpq17b/
Array(number) creates an empty array of [number] places
Array.from(arr, (_, i) => i) populates the empty array with values according to position [0,1,2,3,4,5,6,7,8,9]
.filter(i => ...) filters the populated [0,1,2,3,4,5] array to the elements which satisfy the condition of number % i === 0 which leaves only the numbers that are the factors of the original number.
Note that you can go just until Math.floor(number/2) for efficiency purposes if you deal with big numbers (or small).
As an even more performant complement to #the-quodesmith's answer, once you have a factor, you know immediately what its pairing product is:
function getFactors(num) {
const isEven = num % 2 === 0;
const max = Math.sqrt(num);
const inc = isEven ? 1 : 2;
let factors = [1, num];
for (let curFactor = isEven ? 2 : 3; curFactor <= max; curFactor += inc) {
if (num % curFactor !== 0) continue;
factors.push(curFactor);
let compliment = num / curFactor;
if (compliment !== curFactor) factors.push(compliment);
}
return factors;
}
for getFactors(300) this will run the loop only 15 times, as opposed to +-150 for the original.
#Moob's answer is correct. You must use a loop. However, you can speed up the process by determining if each number is even or odd. Odd numbers don't need to be checked against every number like evens do. Odd numbers can be checked against every-other number. Also, we don't need to check past half the given number as nothing above half will work. Excluding 0 and starting with 1:
function calculate(num) {
var half = Math.floor(num / 2), // Ensures a whole number <= num.
str = '1', // 1 will be a part of every solution.
i, j;
// Determine our increment value for the loop and starting point.
num % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2);
for (i; i <= half; i += j) {
num % i === 0 ? str += ',' + i : false;
}
str += ',' + num; // Always include the original number.
console.log(str);
}
calculate(232);
http://jsfiddle.net/r8wh715t/
While I understand in your particular case (calculating 232) computation speed isn't a factor (<-- no pun intended), it could be an issue for larger numbers or multiple calculations. I was working on Project Euler problem #12 where I needed this type of function and computation speed was crucial.
function calculate(num) {
var str = "0";
for (var i = 1; i <= num; i++) {
if (num % i == 0) {
str += ',' + i;
}
}
alert(str);
}
calculate(232);
http://jsfiddle.net/67qmt/
Below is an implementation with the time complexity O(sqrt(N)):
function(A) {
var output = [];
for (var i=1; i <= Math.sqrt(A); i++) {
if (A % i === 0) {
output.push(i);
if (i !== Math.sqrt(A)) output.push(A/i);
}
}
if (output.indexOf(A) === -1) output.push(A);
return output;
}
here is a performance friendly version with complexity O(sqrt(N)).
Output is a sorted array without using sort.
var factors = (num) => {
let fac = [], i = 1, ind = 0;
while (i <= Math.floor(Math.sqrt(num))) {
//inserting new elements in the middle using splice
if (num%i === 0) {
fac.splice(ind,0,i);
if (i != num/i) {
fac.splice(-ind,0,num/i);
}
ind++;
}
i++;
}
//swapping first and last elements
let temp = fac[fac.length - 1];
fac[fac.length - 1] = fac[0];
fac[0] = temp;
// nice sorted array of factors
return fac;
};
console.log(factors(100));
Output:
[ 1, 2, 4, 5, 10, 20, 25, 50, 100 ]
This got me an 85% on Codility (Fails on the upperlimit, over a billion).
Reducing the input by half doesn't work well on large numbers as half is still a very large loop. So I used an object to keep track of the number and it's half value, meaning that we can reduce the loop to one quarter as we work from both ends simultaneously.
N=24 becomes: (1&24),(2&12),(3&8),(4&6)
function solution(N) {
const factors = {};
let num = 1;
let finished = false;
while(!finished)
{
if(factors[num] !== undefined)
{
finished = true;
}
else if(Number.isInteger(N/num))
{
factors[num] = 0;
factors[N/num]= 0;
}
num++
}
return Object.keys(factors).length;
}
Using generators in typescript in 2021
function* numberFactorGenerator(number: number): Generator<number> {
let i: number = 0;
while (i <= number) {
if (number % i === 0) {
yield i;
}
i++;
}
}
console.log([...numberFactorGenerator(12)]); // [ 1, 2, 3, 4, 6, 12 ]
function factorialize(num) {
var result = '';
if( num === 0){
return 1;
}else{
var myNum = [];
for(i = 1; i <= num; i++){
myNum.push(i);
result = myNum.reduce(function(pre,cur){
return pre * cur;
});
}
return result;
}
}
factorialize(9);
I came looking for an algorithm for this for use in factoring quadratic equations, meaning I need to consider both positive and negative numbers and factors. The below function does that and returns a list of factor pairs. Fiddle.
function getFactors(n) {
if (n === 0) {return "∞";} // Deal with 0
if (n % 1 !== 0) {return "The input must be an integer.";} // Deal with non-integers
// Check only up to the square root of the absolute value of n
// All factors above that will pair with factors below that
var absval_of_n = Math.abs(n),
sqrt_of_n = Math.sqrt(absval_of_n),
numbers_to_check = [];
for (var i=1; i <= sqrt_of_n; i++) {
numbers_to_check.push(i);
}
// Create an array of factor pairs
var factors = [];
for (var i=0; i <= numbers_to_check.length; i++) {
if (absval_of_n % i === 0) {
// Include both positive and negative factors
if (n>0) {
factors.push([i, absval_of_n/i]);
factors.push([-i, -absval_of_n/i]);
} else {
factors.push([-i, absval_of_n/i]);
factors.push([i, -absval_of_n/i]);
}
}
}
// Test for the console
console.log("FACTORS OF "+n+":\n"+
"There are "+factors.length+" factor pairs.");
for (var i=0; i<factors.length; i++) {
console.log(factors[i]);
}
return factors;
}
getFactors(-26);
function calculate(num){
var str = "0" // initializes a place holder for var str
for(i=2;i<num;i++){
var num2 = num%i;
if(num2 ==0){
str = str +i; // this line joins the factors to the var str
}
}
str1 = str.substr(1) //This removes the initial --var str = "0" at line 2
console.log(str1)
}
calculate(232);
//Output 2482958116
Here's an optimized solution using best practices, proper code style/readability, and returns the results in an ordered array.
function getFactors(num) {
const maxFactorNum = Math.floor(Math.sqrt(num));
const factorArr = [];
let count = 0; //count of factors found < maxFactorNum.
for (let i = 1; i <= maxFactorNum; i++) {
//inserting new elements in the middle using splice
if (num % i === 0) {
factorArr.splice(count, 0, i);
let otherFactor = num / i; //the other factor
if (i != otherFactor) {
//insert these factors in the front of the array
factorArr.splice(-count, 0, otherFactor);
}
count++;
}
}
//swapping first and last elements
let lastIndex = factorArr.length - 1;
let temp = factorArr[lastIndex];
factorArr[lastIndex] = factorArr[0];
factorArr[0] = temp;
return factorArr;
}
console.log(getFactors(100));
console.log(getFactors(240));
console.log(getFactors(600851475143)); //large number used in Project Euler.
I based my answer on the answer written by #Harman
We don't have to loop till end of the given number to find out all the factors. We just have to loop till reaching the given number's squareroot. After that point we, can figure out the rest of the factors by dividing the given number with the already found factors.
There is one special case with this logic. When the given number has a perfect square, then the middle factor is duplicated. The special case is also handled properly in the below code.
const findFactors = function (num) {
const startingFactors = []
const latterFactors = []
const sqrt = Math.sqrt(num)
for (let i = 1; i <= sqrt; i++) {
if (num % i == 0) {
startingFactors.push(i)
latterFactors.push(num / i)
}
}
// edge case (if number has perfect square, then the middle factor is replicated, so remove it)
if (sqrt % 1 == 0) startingFactors.pop()
return startingFactors.concat(latterFactors.reverse())
}
function factorialize(num) {
if(num === 0)
return 1;
var arr = [];
for(var i=1; i<= num; i++){
arr.push(i);
}
num = arr.reduce(function(preVal, curVal){
return preVal * curVal;
});
return num;
}
factorialize(5);