function that checks if a number is narcisstic or not - javascript

I run the code multiple times but couldn't find the problem!!
A Narcissistic Number is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).
Your code must return true or false (not 'true' and 'false') depending upon whether the given number is a Narcissistic number in base 10.
function narcissistic(value) {
let strDigits = value.toString();
let power = strDigits.length;
let arrayDigits = strDigits.split('');
let sum, poweredValue = 0;
for (let i = 0; i < power; i++){
poweredValue = Number(arrayDigits[i])**power;
sum += poweredValue;
}
if (sum === value){
return true;
}else {
return false;
}
};

You have to assign the initial value for sum as 0. By default, it's set to undefined. And adding something to undefined gives NaN, and any comparison with NaN is always false.
function narcissistic(value) {
let strDigits = value.toString();
let power = strDigits.length;
let arrayDigits = strDigits.split("");
let sum = 0,
poweredValue = 0;
for (let i = 0; i < power; i++) {
poweredValue = Number(arrayDigits[i]) ** power;
sum += poweredValue;
}
if (sum === value) {
return true;
} else {
return false;
}
}

You assumed that the statement of the form:
let x, y =0;
initialize x and y both as 0. But x is still undefined.
And type undefined + type number will evaluate to NaN (not a number).
And no number is equal to NaN
Just initialize properly:
function narcissistic(value) {
let strDigits = value.toString();
let power = strDigits.length;
let arrayDigits = strDigits.split('');
let sum =0, poweredValue = 0;
for (let i = 0; i < power; i++){
poweredValue = Number(arrayDigits[i])**power;
sum += poweredValue;
}
if (sum === value){
return true;
}else {
return false;
}
};
console.log(narcissistic(153));

Something like that?
const n = 153
function action(n) {
let sum = 0;
n.toString().split('').forEach(i => {
sum += parseInt(i)**n.toString().length;
})
return sum == n
}
console.log(action(n))

Related

Cheking if it's a prime number with JS

I'm first trying to push only prime numbers (without 2) to an array and then sum them all but getting undefined.
I've been working on this for long days, I'd appreciate if anyone could help me.
let letsCheck = () => {
let ourList = []
let sum = 0
for(let i = 2; i <= 50; i++) {
if(i % 2 !== Number.isInteger()) {
ourList.push(Number(i))
}
}
for(let prime in ourList) {
sum += ourList[prime]
}
}
First of all, You are not checking prime but checking odd numbers by % operator.
Second, you are checking Number.isNumber function which will return the boolean so, the comparison have some issues.
Here is one solution which may help.
let letsCheck = () => {
let ourList = []
let sum = 0
for(let i = 3; i <= 50; i++) {
if(isPrimeNumber(i)) {
ourList.push(Number(i))
}
}
for(let prime in ourList) {
sum += ourList[prime]
}
}
const isPrimeNumber = number => {
for(let i = 2; i <= Math.ceil(number/2); i++) {
if(number % 2 === 0) {
return false;
}
}
return true;
}
From, your code, it was more likely for obtaining odd/even numbers instead of prime numbers.
Prime numbers are whole numbers greater than 1, that have only two factors – 1 and the number itself
Odd numbers are the numbers that doesn't have 2 as its factor, and will have remainder = 1 if it gets divided by 2.
Then, as the basic programming math, the mod works like multiplication/add/subtraction that if both operators/numbers are Integer, the result would be Integer. The mod operation is basically for obtaining the remainders from the division, i.e. 5 / 2 = 2, with remainders = 1, thus 5 % 2 = 1.
And, in the looping, the i is already a number, so pushing the Number(i) is equivalent with pushing i alone. If you just want to get the sum, the array is not necessary there and should be just removed. You can get the sum by accumulate it into the sum variable.
Thus, if you wish to get the sum of odd numbers in the range [2,50], it should be:
let letsCheck = () => {
let sum = 0
for(let i = 2; i <= 50; i++) {
if(i % 2 !== 0) {
sum += i;
}
}
console.log(sum);
}
letsCheck();
And if you wish to get the prime numbers from 0 to 50 excluding 2, it should be:
function isPrimeExclude2(num) {
if(num <= 2) return false;
for(let i=2; i*i <= num; i++){
if (num % i == 0) return false;
}
return true;
}
let letsCheck = () => {
let sum = 0
for(let i = 2; i <= 50; i++) {
if(isPrimeExclude2(i)) {
sum = sum + i;
}
}
console.log(sum);
}
letsCheck();

Digital Root exercise on Javascript

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))

Check Digit Sum Javascript- recursion [duplicate]

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);

function sumDigits; How do I get this function to work with a negative number?

Question:
Write a function called sumDigits.
Given a number, sumDigits returns the sum of all its digits.
var output = sumDigits(1148);
console.log(output); // --> 14
If the number is negative, the first digit should count as negative.
var output = sumDigits(-316);
console.log(output); // --> 4
This is what I currently have coded and it works for positive values but I can't wrap my head around how to tackle the problem when given a negative value. When -316 is put into the function, NaN is returned and I understand that when I toString().split('') the number, this is what is returned: ['-', '3', '1', '6']. How do I deal with combining index 0 and 1?
function sumDigits(num) {
var total = 0;
var newString = num.toString().split('');
for (var i = 0; i < newString.length; i ++) {
var converted = parseInt(newString[i]);
total += converted;
}
return total;
}
sumDigits(1148);
Any hints on what methods I should be using? and is there a smarter way to even look at this?
This should do it:
function sumDigits(num) {
var total = 0;
var newString = num.toString().split('');
for (var i = 0; i < newString.length; i ++) {
if(newString[i]==='-') { //check to see if the first char is -
i++; //if it is, lets move to the negative number
var converted = parseInt(newString[i]); // parse negative number
total -= converted; // subtract value from total
continue; // move to the next item in the loop
}
var converted = parseInt(newString[i]);
total += converted;
}
return total;
}
console.log(sumDigits(-316));
You could always use String#replace with a function as a parameter:
function sumDigits (n) {
var total = 0
n.toFixed().replace(/-?\d/g, function (d) {
total += +d
})
return total
}
console.log(sumDigits(-1148)) //=> 14
One way to do this, is to do a split that will keep the minus and the first digit together, not split.
You can do that with a regular expression, and use match instead of split:
var newString = num.toString().match(/-?\d/g);
function sumDigits(num) {
var total = 0;
var newString = num.toString().match(/-?\d/g);
for (var i = 0; i < newString.length; i++) {
var converted = parseInt(newString[i]);
total += converted;
}
return total;
}
var result = sumDigits(-316);
console.log(result);
In a bit shorter version, you could use map and reduce, like this:
function sumDigits(num) {
return String(num).match(/-?\d/g).map(Number).reduce( (a, b) => a+b );
}
console.log(sumDigits(-316));
Is there a smarter way to even look at this?
You can avoid the conversion from number to string and back by using the modulo operator to extract the last digit. Repeat this step until you got all digits:
function sumDigits(num) {
let total = 0, digit = 0;
while (num != 0) {
total += digit = num % 10;
num = (num - digit) * 0.1;
}
return total < 0 ? digit + digit - total : total;
}
console.log(sumDigits(-316)); // 4
console.log(sumDigits(1148)); // 14
console.log(sumDigits(Number.MAX_SAFE_INTEGER)); // 76
function sumDigits(num) {
let string = num.toString();
let zero = 0;
let total = 0;
for (var i = 0; i < string.length; i++) {
if (Math.sign(num) === 1) {
total = zero += Number(string[i]);
} else {
for (var i = 2; i < string.length; i++) {
total = (zero += Number(string[i])) - Number(string[1]);
}
}
}
return total;
}

JavaScript Function Arrays

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

Categories

Resources