@JeremyLT thanks, but now, while loop is changing the elements in array one by one. How can I divide all elements by the number, until all the elements are-
arr[j] % i !== 1.
function collectNumsInArray(arr){
let arr1 = []
for(let i = Math.min(...arr); i <= Math.max(...arr); i++){
arr1.push(i);
}
return arr1;
}
function sumCommonsNums(arr){
let arr1 = collectNumsInArray(arr);
let lcm = 1;
console.log(arr1)
for(let i = 2; i <= arr1[arr1.length - 1]; i++){
for(let j = 0; j <= arr1.length; j++){
while (arr1[j] % i === 0){
arr1[j] = arr1[j] / i;
console.log(arr1)
lcm *= i;
console.log(i)
}
}
}
}
sumCommonsNums([1, 5])
You want to check for every j what exactly? arr1[j] % i ===0 - this?
And if the above is true for every j, only then you want to execute accumulation like below?
Hi Thanks for replying,
So I want the function to be like this -
check for elements – elements % === 0.
Divide those elements by that number.
Accumulate
Then check again for that number until elements % !== 0.
and repeat.
That’s how I have been calculating LCM-
example - range 1 to 5
2 | 1 2 3 4 5
2 | 1 1 3 2 5
3 | 1 1 3 1 5
5 | 1 1 1 1 5
| 1 1 1 1 1
LCM 2 * 2* 3 * 5 = 60
This is the method, I am trying to translate to code.
That’s interesting. The thing is: I solved this problem literally an hour ago, but I used slightly different math.
I will try to implement your method, and if succeed, I will be able to provide some hints for you.
As I see it now, I will use methods like
UPDATE Array.prototype.filter() also can be useful
Thank you so much. Yea, I think there are lots of ways to find out LCM. The solution 1, I thinks calculates two elements in the range and then move on to the next one which is interesting but I really want to solve it by the method I am trying.
If you trying to do a prime factorization of each number in the range, then you will need to keep a separate total of how many times each factor appears. I don’t understand this chart, so I’m not really sure what you see as the mathematical algorithm you are trying to replicate.
if at least one element in array is evenly divisible by i===2
we need to:
accumulate lcm
change an array like [1, 2, 3, 4, 5] >>> [1, 1, 3, 2, 5] meaning divide by 2 every elem if it’s divided by 2 evenly
The block above need to be repeated until every elem is not divisible by 2 evenly
then we move to the next i(looping through i - i guess it should be inner *for* loop)
The whole thing must be stopped when every element in array === 1(i guess it should be condition for outer *while* loop)
BTW I am not really big fan of this approach, feels like too many loop inside the loop inside the loop things. But it’s interesting to implement it