This question already has answers here:
Adding digits from a number, using recursivity - javascript
(6 answers)
Closed 8 months ago.
Looking for Javascript solution in recursion to get the sum of all digits in number until single digit come as result
For example, for the number is "55555" the sum of all digits is 25. Because this is not a single-digit number, 2 and 5 would be added, and the result, 7.
I tried the below solution based on the algorithm.
function getSum(n) {
let sum = 0;
while(n > 0 || sum > 9)
{
if(n == 0)
{
n = sum;
sum = 0;
}
sum += n % 10;
n /= 10;
}
return sum;
}
console.log(getSum("55555"));
This would kind of work, but I'm almost sure there's a beautiful one-line solution which I just don't see yet.
function singleDigitSum(str) {
str = [...str].reduce((acc, c) => { return Number(c) + acc }, 0)
while (str.toString().length > 1) {
str = singleDigitSum(str.toString());
}
return str
}
console.log(singleDigitSum("55555"))
Explanation:
As a first step in your function you reassign to the parameter passed to the function the result of a reducer function which sums up all numbers in your String. To be able to use Array.prototype.reduce() function, I'm spreading your str into an array using [...str].
Then, for as often as that reducer returns a value with more than one digit, rinse and repeat. When the while loop exits, the result is single digit and can be returned.
function checSumOfDigit(num, sum = "0") {
if (num.length == 1 && sum.length !== 1) {
return checSumOfDigit(Number(sum) + Number(num) + "", "0");
} else if (num.length == 1) {
return Number(sum) + Number(num);
}
num = num.split("")
sum = Number(sum) + Number(num.pop());
return checSumOfDigit(num.join(""), sum + "")
}
console.log(checSumOfDigit("567"));
console.log(checSumOfDigit("123"));
console.log(checSumOfDigit("55555"));
this code might be help you
If you need a recursion try this one
function CheckDigitSum(number) {
let nums = number.split('');
if (nums.length > 1) {
let sum = 0;
for (let i = 0; i < nums.length; i++) {
sum += Number(nums[i]);
}
return CheckDigitSum(sum.toString());
} else {
return parseInt(nums[0], 10);
}
}
Here you go:
function createCheckDigit(num) {
var output = Array.from(num.toString());
var sum = 0;
if (Array.isArray(output) && output.length) {
for ( i=0; i < output.length; i++){
sum = sum + parseInt(output[i]);
}
if ((sum/10) >= 1){
sum = createCheckDigit(sum);
}
}
return sum;
}
This can be calculated by recursive function.
function createCheckDigit(membershipId) {
// Write the code that goes here.
if(membershipId.length > 1){
var dgts = membershipId.split('');
var sum = 0;
dgts.forEach((dgt)=>{
sum += Number(dgt);
});
//console.log('Loop 1');
return createCheckDigit(sum + '');
}
else{
//console.log('Out of Loop 1');
return Number(membershipId);
}
}
console.log(createCheckDigit("5555555555"));
function checkid(num) {
let sum = 0;
let s = String(num);
for (i = 0; i < s.length; i++) {
sum = sum + Number(s[i]);
}
if(String(sum).length >= 2) return checkid(sum)
else return sum;
}
console.log(checkid(55555);
Related
Question
A prime number is a whole number greater than 1 with exactly two divisors: 1 and itself. For example, 2 is a prime number because it is only divisible by 1 and 2. In contrast, 4 is not prime since it is divisible by 1, 2 and 4.
Rewrite sumPrimes so it returns the sum of all prime numbers that are less than or equal to num.
My Attempt
const isPrime = a => {
for(let i = 2; i < a; i++)
if(num % i === 0) return false;
return a > 1;
}
function sumPrimes(num, total = []) {
let numVar = num;
let n = total.reduce((aggregate, item)=>{
return aggregate + item;
}, 0);
if(n > numVar){
return n;
}
for(let i = 1; i <= numVar; i++){
if(isPrime(i)== true){
total.push(i);
}
}
return sumPrimes(num, total);
}
sumPrimes(10);
The Problem
It says: 'Num is not defined'
I am not sure if there are other errors.
My Question
Please could you help me find the error, and fix the code to solve the algorithm?
This was a simple syntax error identified by #Jonas Wilms (upvote him in the comment above :))!
By replacing the 'a' with 'num' the function was fixed.
const isPrime = a => {
for(let i = 2; i < a; i++)
if(a % i === 0) return false;
return a > 1;
}
function sumPrimes(num, total = []) {
let numVar = num;
let n = total.reduce((aggregate, item)=>{
return aggregate + item;
}, 0);
if(n > numVar){
return n;
}
for(let i = 1; i <= numVar; i++){
if(isPrime(i)== true){
total.push(i);
}
}
return sumPrimes(num, total);
}
console.log(sumPrimes(10));
this simple function may help you,
function isPrime(num) {
for (var i = 2; i < num; i++)
if (num % i === 0) return false;
return num > 1;
}
function sumPrimes(num) {
let tot = 0;
for (let i = 0; i < num; i++)
if (isPrime(i))
tot += i;
return tot;
}
console.log(sumPrimes(10));
I'm having some trouble trying to do a digital root exercise on Javascript.
Here's my code:
function digital_root(n) {
var sNumero = n.toString();
var sum = 0;
for(i = 0 ; i < sNumero.length; i++){
sum += parseInt(sNumero[i]);
}
if(sum > 9){
digital_root(sum);
}
return sum;
}
When I try to input 456 to 'n', the function gives 15 as the return. The expected is 6. I don't know why this is happening.
To help you guys understand my problem, here's the exercise:
"A digital root is the recursive sum of all the digits in a number. 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. This is
only applicable to the natural numbers."
You forgot a return:
if(sum > 9){
return digital_root(sum); // <-- here
}
You can add a return statement here on
function digital_root(n) {
var sNumero = n.toString();
var sum = 0;
for (i = 0; i < sNumero.length; i++) {
sum += parseInt(sNumero[i]);
}
if (sum > 9) {
return digital_root(sum); // missing return here
}
return sum;
}
console.log(digital_root(456))
OR add a new variable to capture the final result before returning.
function digital_root(n) {
var sNumero = n.toString();
var sum = 0;
var final_result; // introduce new variable to hold recursive sum
for (i = 0; i < sNumero.length; i++) {
sum += parseInt(sNumero[i]);
}
final_result = sum; // assign sum to final_result variable
if (sum > 9) {
final_result = digital_root(sum);
}
return final_result; // return final_result
}
console.log(digital_root(456))
I'm taking the freecodecamp course one of the exercises it's to create a Factorialize function, I know there is several ways to do it just not sure what this one keeps returning 5
function factorialize(num) {
var myMax = num;
var myCounter = 1;
var myTotal = 0;
for (i = 0; i>= myMax; i++) {
num = myCounter * (myCounter + 1);
myCounter++;
}
return num;
}
factorialize(5);
This is a recursive solution of your problem:
function factorialize(num) {
if(num <= 1) {
return num
} else {
return num * factorialize(num-1)
}
}
factorialize(5)
This is the iterative solution:
function factorialize(num) {
var cnt = 1;
for (var i = 1; i <= num ; i++) {
cnt *= i;
}
return cnt;
}
factorialize(5)
with argument 5, it will return the 5! or 120.
To answer your question, why your function is returning 5:
Your function never reaches the inner part of the for-loop because your testing if i is greater than myMax instead of less than.
So you are just returning your input parameter which is five.
But the loop does not calculate the factorial of num, it only multiplies (num+1) with (num+2);
My solution in compliance with convention for empty product
function factorializer(int) {
if (int <= 1) {
return 1;
} else {
return int * factorializer(int - 1);
}
}
Here is another way to solve this challenge and I know it is neither the shortest nor the easiest but it is still a valid way.
function factorialiaze(num){
var myArr = []; //declaring an array.
if(num === 0 || num === 1){
return 1;
}
if (num < 0){ //for negative numbers.
return "N/A";
}
for (var i = 1; i <= num; i++){ // creating an array.
myArr.push(i);
}
// Reducing myArr to a single value via .reduce:
num = myArr.reduce(function(a,b){
return a * b;
});
return num;
}
factorialiaze(5);
Maybe you consider another approach.
This solution features a very short - cut to show what is possible to get with an recursive style and a implicit type conversion:
function f(n) { return +!~-n || n * f(n - 1); }
+ convert to number
! not
~ not bitwise
- negative
function f(n) { return +!~-n || n * f(n - 1); }
var i;
for (i = 1; i < 20; i++) {
console.log(f(i));
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this function
const factorialize = (num) => num === 0 ? 1 : num * factorialize(num-1)
Use it like this:
factorialize(5) // returns 120
Try this :
function factorialize(num) {
var value = 1;
if(num === 1 || num ===0) {
return value;
} else {
for(var i = 1; i<num; i++) {
value *= i;
}
return num * value;
}
}
factorialize(5);
// My solution
const factorialize = num => {
let newNum = 1;
for (let i = 1; i <= num; i++) {
newNum *= i
}
return newNum;
}
I love syntactic sugar, so
let factorialize = num => num <= 1 ? num : num * factorialize(num -1)
factorialize(5)
How would I use a function that returns the sum of a given array while getting the sum of the even numbers and sum the odd numbers? I'm not understanding how that is done. Can someone please explain a little more in depth?
Here is my entire code:
function main()
{
var evenNum = 0;
//need a total Even count
var oddNum = 0;
//need a total Odd count
var counter = 1;
var num = 0;
function isOdd(x) {
if ((num % 2) == 0)
{
return false;
}
else
{
return true;
}
}
function isEven(x) {
if ((num % 2) == 0)
{
return false;
}
else
{
return true;
}
}
for (counter = 1; counter <= 100; counter++)
{
num = Math.floor(1 + Math.random() * (100-1));
var total = 0;
for(var j = 0; j < length; j++)
total += a[j];//Array?
console.log(num);
console.log("The count of even number is " + evenNum);
console.log("The count of odd number is " + oddNum);
return 0;
}
main()
If I understand your question correctly, you need a function that returns two values, one for the sum of even numbers and one for the sum of odd numbers. It's not clear if you use even/odd referring to the index of the array or the values in array.
In both cases you can return an object that contains both values:
function sum(array) {
var evenSum = 0;
var oddSum = 0;
...calculate...
var res = {};
res.evenSum = evenSum;
res.oddSum = oddSum;
return res;
}
Hope this will help
Here I have a function that should take a number n into the disHappy(n) to check if all
n in [n-0) are happy.
Happy Numbers wikipedia
If I only run happyChecker(n), I can tell that 7 is happy, but disHappy(n) doesn't show it. It is as if it doesn't receive the true. I have used console.log()'s all over the place and happyChecker(n) shows a number that SHOULD return true. When I placed a console.log() above the return true; for if(newNum===1), it showed that it branched into that branch but it just didn't seem to return the true.
function happyChecker(n) {
var arr = [];
var newNum = 0;
//here I split a number into a string then into an array of strings//
num = n.toString().split("");
for (var i = 0; i < num.length; i++) {
arr[i] = parseInt(num[i], 10);
}
//here I square each number then add it to newNum//
for (var i = 0; i < arr.length; i++) {
newNum += Math.pow(arr[i], 2);
}
//here I noticed that all unhappy numbers eventually came into one of these three//
//( and more) numbers, so I chose them to shorten the checking. A temporary solution for sure//
if (newNum === 58 || newNum === 4 || newNum == 37) {
return false;
}
if (newNum === 1) {
return true;
} else {
happyChecker(newNum);
}
}
function disHappy(num) {
for (j = num; j > 0; j--) {
if (happyChecker(j)) {
console.log(j + " is a Happy Number. It's so happy!!!.");
}
}
}
When you recurse, you need to return the value returned:
if (newNum === 1) {
return true;
} else {
return happyChecker(newNum);
}
You also should declare "num" with var.
I'm ordinarily not a "code golfer", but this is a good example of how the (new-ish) iterator utility methods on the Array prototype can clean up code. You can use the .reduce() function to traverse the array of digit characters and do the work of squaring and summing all at once:
var newNum = n.toString()
.split('')
.reduce(function(sum, digit) {
return sum + (+digit * +digit);
}, 0);
The call to .toString() returns a string, then .split('') gives you an array. Then .reduce() starts with an initial sum of 0 and for each element of the array (each digit), it adds to it the square of that digit. (Instead of parseInt() I just used the + unary operator; we know for sure that each string will be a valid number and an integer.)
You need to add return to the happyChecker call.
return happyChecker(newNum);
see:
http://jsfiddle.net/YjgL8/2/
here is my implementation
var getSum = function (n) {
if (!n >= 0) return -1;
var digits = n.toString().split("");
var sum = 0;
for (var i = 0; i < digits.length; i++) {
var digit = parseInt(digits[i], 10);
sum += digit * digit;
}
return sum;
}
/**
* #param {number} n
* #return {boolean}
*/
var isHappy = function(n, visited) {
if (n < 0) return false;
if (n === 1) return true;
if (typeof visited === 'undefined') visited = {};
sum = getSum(n);
if (visited[sum]) return false; // cycle
visited[sum] = true;
return isHappy(sum, visited);
};
Complete Example of finding happy numbers in range of custom number.
function happyNumbers() {
var result = document.getElementById("happy-result")
var inputy = parseInt(document.getElementById("happyValue").value)
result.innerHTML=""
for (i = 1; i < inputy; i++) {
(happy(i, i))
}
}
function happy(value,value2) {
var result = document.getElementById("happy-result")
var lengthNum = value.toString().length;
var resultNumbers = 0
for (var b = 0 ; b < lengthNum; b++) {
resultNumbers = resultNumbers + parseInt(value.toString().charAt(b)) * parseInt(value.toString().charAt(b))
}
if (resultNumbers == 4) {
return false
} else if (resultNumbers == 1) {
result.innerHTML += "<br> happy number " + i
return true
}else{
happy(resultNumbers, value2);
}
}
window.onload=happyNumbers()
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="panel panel-default">
<div class="panel-heading">happy numbers</div>
<div class="panel-body">
<label>Enter the number that you want ot have see happy numbers uo to it</label>
<input id="happyValue" oninput="happyNumbers()" value="100" class="form-control" />
<div id="happy-result"></div>
</div>
</div>