Question : Given n, take the sum of the digits of n. If that value has
more than one digit, continue reducing in this way until a
single-digit number is produced. The input will be a non-negative
integer. Ex- 16 --> 1 + 6 = 7 942 --> 9 + 4 + 2 = 15 --> 1 +
5 = 6 132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6 493193
--> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2
function digitalroot(n) {
let a = n;
var sum = 0;
while(a >= 1){
sum += a % 10;
a = Math.trunc(a/10)
}
if(sum > 9){
digitalroot(sum)
}
console.log("Print")
console.log(sum)
return sum
}
I tried above code but not getting correct output with below called input
With this two inputs passed in function: (16), (456)
O/P:
Print
7
Print
6
Print
15
Please help me, I am new to JavaScript
you forgot to return value from function call inside that sum>9 condition.
check recursion here : w3School
function digitalroot(n) {
let a = n;
var sum = 0;
while(a >= 1){
sum += a % 10;
a = Math.trunc(a/10)
}
if(sum > 9){
return digitalroot(sum)
}
return sum
}
console.log(digitalroot(493193));
Check this working example
function digitalroot(n){
console.log(`Value of n = ${n}`)
var digits = (""+n).split("");
for (var i = 0; i < digits.length; i++) {
digits[i] = +digits[i];
}
var finalVal = digits
let result = finalVal.reduce((a, b) => a + b, 0)
console.log(`Final Value with list ${result}`)
}
digitalroot(289)
Related
It is a counter function for descending number. I throw any number and it start to countdown to zero and I add space between them but the Problem is the last space! How can I remove it??
function countDown(number) {
var s = "";
for (let i = number; i >= 0; i--) {
s += i + " ";
}
console.log("{" + s + "}"); // I add the brackets to show the last space
}
countDown(10)
// result is : {10 9 8 7 6 5 4 3 2 1 0 }
This is a great use case for the Array.join function.
function countDown(number) {
const list = [];
for (let i = number; i >= 0; i--) {
list.push(i);
}
console.log("{" + list.join(' ') + "}");
}
countDown(10)
// result is : {10 9 8 7 6 5 4 3 2 1 0}
This is a common pattern that one has to deal with in loops.
Typically you solve this by having a special case in the beggining or end of a loop. In this example it is easy just to have one in the beggining:
function countDown(number) {
var s = number;
for (let i = number - 1; i >= 0; i--) {
s += " " + i;
}
console.log("{" + s + "}"); // I add the brackets to show the last space
}
countDown(10)
// result is : {10 9 8 7 6 5 4 3 2 1 0}
Just assign s to the number in the beggining and decrease the starting number by 1.
With "low-level" Javascript, without builtins, the trick is to add a delimiter before an item, not after it:
function countDown(number) {
let s = String(number)
for (let i = number - 1; i >= 0; i--)
s += ' ' + i
return s
}
console.log(JSON.stringify(countDown(10)))
If builtins are allowed, you don't even need a loop to produce this result:
result = [...new Array(11).keys()].reverse().join(' ')
console.log(result)
I am trying to figure out a triangle excercise where the user inputs a number and the triangle is then created based on said number ex enter 5
This is what I want
**5
6 6
7 7 7
8 8 8 8
9 9 9 9 9
10 10 10 10 10**
Each line the number is increased by 1. I can't get my code to increase by 1.
I keep getting
5
5 5
5 5 5
5 5 5 5
5 5 5 5 5
Anyone have any suggestions? Thanks
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (i = 1; i <= 6; i++) {
//loop 2
for (y = 0; y < i; y++) {
document.write(num);
}
document.write(num = num +1; "<br>");
}
<p id="num"> </p>
You just have to use the entered number as the loop upper limit:
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (i = 1; i <= num; i++) {
//loop 2
for (y = 0; y < i; y++) {
document.write(num);
}
document.write("<br>");
}
This syntax is entirely invalid:
document.write(num = num +1; "<br>");
You're somehow confusing calling a function with defining a for loop. Those are two entirely different things.
Don't randomly try to munge together separate operations. Put each operation on its own line of code. The two operations you want to perform are:
Add 1 to num
Output a <br> element
These are separate operations. So separate them:
num = num +1;
document.write("<br>");
You don't seem to be placing the incrementation of your num before writing it to the document. See the code below check the line between loops.
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (let i = 1; i <= 6; i++) {
//loop 2
num++;
for (let y = 0; y < i; y++) {
document.write(num);
}
document.write("<br>");
}
<p id="num"> </p>;
const reversedNum = num =>
parseFloat(num.toString().split('').reverse().join('')) * Math.sign(num)
console.log(reversedNum(456))
Couldn't figure it out how to write code in order to sum 654 + 456
Thank You very much!
const reversedNum = num => num + +num.toString().split('').reverse().join('')
You can return sum of num and reversedNum inside a function.
const sumOfNumAndReversedNum= num => {
const reversedNum = parseFloat(num.toString().split('').reverse().join('')) * Math.sign(num)
return num + reversedNum
}
let userNumber = 456
console.log(sumOfNumAndReversedNum(userNumber))
You can write a more performant way of reversing the number than turning it into a string, flipping it, and turning it back into an integer.
One option is to go through the number backwards by popping off the last integer (e.g., 123 % 10 === 3) and adding it to your newly reversed number. You'll also need to multiply your reversed number by 10 in each iteration to move you to the next degree.
For example, given the number 123:
123 % 10 = 3;
123 /= 10 = 12;
0 * 10 + 3 = 3;
1 % 10 = 2;
12 /= 10 = 1;
3 * 10 + 2 = 32
1 % 10 = 1;
1 /= 10 = 0;
32 * 10 + 1 = 321
This method will also automatically take care of negative numbers for you, leaving you something like:
function reverse(num) {
let reversed = 0;
while (num !== 0) {
const popped = num % 10;
num = parseInt(num / 10);
if (reversed > Number.MAX_VALUE / 10 || (reversed === Number.MAX_VALUE / 10 && popped > 7)) return 0;
if (reversed < Number.MIN_VALUE / 10 || (reversed === Number.MIN_VALUE / 10 && popped < -8)) return 0;
reversed = reversed * 10 + popped;
}
return reversed;
}
Now you can simply call:
console.log(123 + reverse(123))
const reversedNum = num =>
Number(num.toString().split('').reverse().join(''))
console.log(reversedNum(456))
Do it!
I have tried this
function binToDec(num) {
let dec = 0;
for(let i = 0; i < num.length; i++) {
if(num[num.length - (i + 1)] === '1') {
dec += 2 ** i;
}
}
return dec;
}
console.log(binToDec('1010'));
this code is not mine and it works but i want to know how it converts the binary number to decimal and it will be very helpful is you could tell me another way to do it.
I have also tried this
function binToDec(num) {
let bin = parseInt(num, 2);
return bin;
}
console.log(binToDec(1010));
I know this also work but i am not looking for this answer.
thank you for your help.
I just starts with the last character of the string and adds the value of this position to the result.
string dec
------ -------
1010 0
0 0
1 0 + 2
0 2
1 2 + 8
------ ------
10
function binToDec(num) {
let dec = 0;
for (let i = 0; i < num.length; i++) {
if (num[num.length - (i + 1)] === '1') {
dec += 2 ** i;
}
}
return dec;
}
console.log(binToDec('1010')); // 10
Another way is to start with the left side of the sting and
multiply the converted value by the base (2) and
add the value of the string.
The result is now the converted number. This works for all bases, as long as the value at the index is converted to a number.
function binToDec(num) {
let dec = 0;
for (let i = 0; i < num.length; i++) {
dec *= 2;
dec += +num[i];
}
return dec;
}
console.log(binToDec('1101')); // 13
Explanation
Think of how base 10 works.
909 = 900 + 9
= (9 * 100) + (0 * 10) + (9 * 1)
= (9 * 10**2) + (0 * 10**1) + (9 * 10**0)
As you can see, a natural number in base 10 can be seen as a sum where each term is in the form of:
digit * base**digit_position
This is true for any base:
base 2 : 0b101 = (0b1 * 2**2) + (0b0 * 2**1) + (0b1 * 2**0)
base 16 : 0xF0F = (0xF * 16**2) + (0x0 * 16**1) + (0xF * 16**0)
Therefore, here is a possible abstraction of a natural number:
function natural_number (base, digits) {
var sum = 0;
for (var i = 0; i < digits.length; i++) {
digit = digits[i];
digit_position = digits.length - (i + 1);
sum += digit * base**digit_position;
}
return sum;
}
> | natural_number(2, [1, 0, 1]) // 1 * 2**2 + 1 * 2**0
< | 5
> | natural_number(10, [1, 0, 1]) // 1 * 10**2 + 1 * 10**0
< | 101
> | natural_number(16, [1, 0, 1]) // 1 * 16**2 + 1 * 16**0
< | 257
Your own function takes only binary numbers (base 2). In this case digit can be either 0 or 1, that's all. We know that it's useless to multiply something by 0 or 1, so the addition can be replaced with:
if (digit === 1) {
sum += 2**digit_position;
}
Which is the equivalent of:
if (num[num.length - (i + 1)] === '1') {
dec += 2 ** i;
}
Do you get it? :-)
Alternative
You don't feel confortable with the exponentiation operator (**)? There is a workaround. Did you ever notice that multiplying a number by 10 is nothing more than shifting its digits one time to the left?
909 * 10 = 9090
Actually, shifting a number to the left boils down to multiplying this number by its base:
number *= base
This is true for any base:
base 2 : 0b11 * 2 = 0b110
base 16 : 0xBEE * 16 + 0xF = 0xBEE0 + 0xF = 0xBEEF
Based on this, we can build an algorithm to convert an array of digits into a number. A trace of execution with [9,0,9] in base 10 as input would look like this:
init | 0 | n = 0
add 9 | 9 | n += 9
shift | 90 | n *= 10
add 0 | 90 | n += 0
shift | 900 | n *= 10
add 9 | 909 | n += 9
Here is a possible implementation:
function natural_number (base, digits) {
var n = 0;
for (var i = 0; i < digits.length; i++) {
n += digits[i];
if (i + 1 < digits.length) {
n *= base;
}
}
return n;
}
Of course this function works the same as before, and there is a good reason for that. Indeed, unroll the for loop that computes [9,0,9] in base 10, you get this:
return ((0 + 9) * 10 + 0) * 10 + 9;
Then expand this expression:
((0 + 9) * 10 + 0) * 10 + 9
= (0 + 9) * 10 * 10 + 0 * 10 + 9
= 9 * 10 * 10 + 0 * 10 + 9
= 9 * 10**2 + 0 * 10**1 + 9 * 10**0
Do you recognize the equation discussed earlier? :-)
Bonus
Reverse function:
function explode_natural_number (base, number) {
var remainder, exploded = [];
while (number) {
remainder = number % base;
exploded.unshift(remainder);
number = (number - remainder) / base;
}
return exploded.length ? exploded : [0];
}
> | explode_natural_number(2, 5)
< | [1, 0, 1]
> | explode_natural_number(3, 5) // base 3 (5 = 1 * 3**1 + 2 * 3**0) :-)
< | [1, 2]
> | explode_natural_number(16, natural_number(16, [11, 14, 14, 15])) // 0xBEEF
< | [11, 14, 14, 15]
String to number and number to string:
function parse_natural_number (number, base) {
var ZERO = 48, A = 65; // ASCII codes
return natural_number(base, number.split("").map(function (digit) {
return digit.toUpperCase().charCodeAt(0);
}).map(function (code) {
return code - (code < A ? ZERO : A - 10);
}));
}
function stringify_natural_number (number, base) {
var ZERO = 48, A = 65; // ASCII codes
return String.fromCharCode.apply(
String, explode_natural_number(base, number).map(function (digit) {
return digit + (digit < 10 ? ZERO : A - 10);
})
);
}
> | stringify_natural_number(parse_natural_number("48879", 10), 16)
< | "BEEF"
> | parse_natural_number("10", 8)
< | 8
More levels of abstraction for convenience:
function bin_to_dec (number) {
return parse_natural_number(number, 2);
}
function oct_to_dec (number) {
return parse_natural_number(number, 8);
}
function dec_to_dec (number) {
return parse_natural_number(number, 10);
}
function hex_to_dec (number) {
return parse_natural_number(number, 16);
}
function num_to_dec (number) {
switch (number[0] + number[1]) {
case "0b" : return bin_to_dec(number.slice(2));
case "0x" : return hex_to_dec(number.slice(2));
default : switch (number[0]) {
case "0" : return oct_to_dec(number.slice(1));
default : return dec_to_dec(number);
}
}
}
> | oct_to_dec("10")
< | 8
> | num_to_dec("010")
< | 8
> | 010 // :-)
< | 8
function dec_to_bin (number) {
return stringify_natural_number(number, 2);
}
> | dec_to_bin(8)
< | "1000"
I wrote a code with javascript for this problem :
"If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000."
but the result is false and i don't know why? can you help me guys
my code is :
function multipleSum(n){
var sum = 0;
for(var i = 1; i<n; i++){
var m3 = 3 * i;
var m5 = 5 * i;
if(m3 < n ){
sum=sum+m3
}
if(m5 < n ){
sum=sum+m5;
}
//if(m3 > n && m5 > n) {console.log(m3,m5,sum);break;}
}
return sum
}
console.log(multipleSum(1000)) //266333 but correct one is 233168 why?
Your logic is flawed. You should be iterating on each number (specified in range), and see if the modulus of the number with 3 or 5 is 0 or not. If modulus is zero, it means the number is divisible.
function multipleSum(n){
var sum = 0;
for(var i = 1; i<n; i++){
if(i % 3 == 0 || i % 5 ==0){ // gives reminder of 0, divisible by either 3 or 5
sum += i; // add in sum if that's the case.
}
}
return sum
}
console.log(multipleSum(1000))
Edit: tried some time understanding why you went with multiply approach, I think you are gathering factors and want to break out early from the loop instead of iterating on entire collection. This should help you:
function multipleSum(n){
var sum = 0;
for(var i = 1; i<n; i++){
var m3 = i * 3;
var m5 = i * 5;
if(m3 > n) break; // breaks early!!
if(m3 < n) sum += m3
if(m5 < n && m5 % 3 != 0) sum += m5; // make sure number is not divisible by 3, say m5 = 15, it will be captured as multiple of 3 anyway, we don't want duplicates.
}
return sum
}
console.log(multipleSum(1000))
Your logic is flawed in the way that, all the multiplications of 3 * 5 is doubled. Remember, you have:
3 * 1
5 * 1
3 * 2
3 * 3
5 * 2
3 * 4
3 * 5
5 * 3 // Here comes the dupe.
I would do this in a different way.
Get all the multiples of 3 in an array.
Get all the multiples of 5 in an array.
Break the loop when both the multiplications are greater than n.
Merge both the arrays.
Remove the duplicates.
Add everything using the .reduce() function.
var num = 1000;
var m3 = [];
var m5 = [];
for (i = 0; i < num; i++) {
if (i * 3 < num)
m3.push(i * 3);
if (i * 5 < num)
m5.push(i * 5);
if (i * 3 > num)
break;
}
m35 = m3.concat(m5);
m35u = m35.filter(function(item, pos) {
return m35.indexOf(item) == pos;
});
console.log(m35u.reduce((a, b) => a + b, 0));
I get 233168 as answer.
You can try this one liner (your home work: explain how this works ;):
console.log(
Array.from({length: 1000})
.reduce( (p, n, i) => p + (i % 3 === 0 || i % 5 === 0 ? i : 0), 0 )
);
Try this, maybe answer you.Thank
const solution = (numb) => {
const collectedNumb = [];
const maxDividing = parseInt(numb / 3);
for (let idx = 1; idx <= maxDividing; idx++) {
const multipled3 = idx * 3;
const multipled5 = idx * 5;
multipled3 < numb && collectedNumb.push(multipled3);
multipled5 < numb && collectedNumb.push(multipled5);
}
const uniqCollected = [...new Set(collectedNumb)].sort((a, b)=> a-b);
console.log(uniqCollected);
const reduced = uniqCollected.reduce((acc, numb) => acc + numb, 0);
return reduced;
};