let a number=153 how we will split these 3 numbers n1,n2,n3 I have tried by-:
let n = 153
let n1 = n % 10;
let n2 = ((n - n1) / 10) % 10;
let n3 = ((n - n1)/10)/10;
I am getting n1 & n2 correct but cannot find n3 please answer it
let a number=153 how we will split these 3 numbers n1,n2,n3 I have tried by-:
let n = 153
let n1 = n % 10;
let n2 = ((n - n1) / 10) % 10;
let n3 = ((n - n1)/10)/10;
I am getting n1 & n2 correct but cannot find n3 please answer it
you can just turn them into a string, split the string and map back to number like this
const number = 153
const [n3, n2, n1] = String(number).split('').map(Number)
console.log(n1, n2, n3)
You'd need to do
const n = 153;
let n1 = n % 10;
let n2 = ((n - n1) / 10) % 10;
let n3 = ((((n - n1) / 10) - n2) / 10) % 10;
console.log(n1, n2, n3)
Easier is like - but that does change n of course
let n = 153;
let n1 = n % 10;
n = (n - n1) / 10;
let n2 = n % 10;
n = (n - n2) / 10;
let n3 = n % 10;
console.log(n1,n2,n3)
Or if you want to be creative
const n = 153;
const [n1, n2, n3] = ((n) => Array.from({length: Math.floor(Math.log10(n)) + 1}, (_, i) => Math.floor(n / (10**i)) % 10))(n);
console.log(n1, n2, n3)
The n3
is correct except it is returning decimal numbers. A parseInt
would do the needful
let n=$('#armstrong')[0].value;
let n1 = n % 10;
let n2 = ((n - n1) / 10) % 10;
let n3 = parseInt(((n - n1)/10)/10);
if(Math.pow(n1,3)+Math.pow(n2,3)+Math.pow(n3,3)===parseInt(n))
console.log(n+' Is Armstrong');
else
console.log(n+' Is not Armstrong');
$('#armstrong').on('input',function(){
let n=this.value;
let length_n=(''+n).length;
var sum=0;
for(var i=0;i<length_n;i++)
{
sum+=Math.pow((''+n)[i],length_n);
}
if(sum===parseInt(n))
console.log(n+' Is Armstrong');
else
console.log(n+' Is not Armstrong');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="armstrong" value="153">