I made a function that substitutes the * for all the numbers from 0 to 9 and then filters all the ones that are divisible by 6 and should return them as strings.. see in: is divisible by 6 it worked quite well but for very large numbers n%6==0
it didn't It works for me... example n= 1234567890123456789012345678*0 which should return ['123456789012345678901234567800', '123456789012345678901234567830', '123456789012345678901234567860', '123456789012345678901234567890']
instead it returns[]
another way to search for multiples of 6 is if they are divisible by 2 and divisible by 3... so I did this function below, since n%2
it doesn't work I didn't slice its last digit either, and for n%3
that I did reduce its digits %3... This is how it worked for the 6 module because of that variant of the 3 and 2 module, although it is somewhat cumbersome, I passed all the tests... so I would like to know how I can work with very large numbers in Javascript because it is not the first time something has happened to me Similary...
function isDivisibleBy6(s) {
let nums=[];
for(let i=0;i<=9;i++){
nums.push(s.replace(/[*]/, `${i}`));
}
return nums.filter(d =>(d.slice(-1)%2==0) && (d.split('').reduce((a,b)=>+a+~~(b))%3==0))
}
console.log('para 41*: '+isDivisibleBy6('41*'));
console.log('para 34234*2: '+isDivisibleBy6('34234*2'));
console.log('para 1234567890123456789012345678*0: '+isDivisibleBy6('1234567890123456789012345678*0'));
I see your logic to try not to check directly if the number is divisible by
6
is fine, you are checking if the last number is divisible by2
and if the sum of all digits is divisible by3
(perhaps this is the purpose of the exercise)The problem you have trying to check if numbers are divisible by
6
is that you're working with really big numbers that exceed the largest number youJavaScript
can safely work with, so the result of any calculation you do with those numbers is going to be be represented in exponential notation other than that you would not be sure that the result is correct:As @ordago recommended, it is best to work with a method that works with numbers of this size safely. The standard already has bigInt , but its compatibility is still very low. It is best to use some library that treats numbers as strings. Normally in HackerRank it is possible to include in the code the big-number library to handle large numbers in
JavaScript
(I don't know if it is available in CodeWars, but if it isn't, your solution is correct as long as the sum of the digits does not exceedNumber.MAX_SAFE_INTEGER
) .Here I leave you the same calculations as before using a similar library ( big-integer ):
And here the code checking if the numbers are divisible by
6
using the same library:And here your same code checking if the last number is divisible by
2
and usingbig-integer
for the sum of the digits in case the sum results in a very large number (it is very unlikely that you will be given a number of this size as input):