I need to do a code to verify whether or not the entered number is an Armstrong number, but my code does not work for every number.
Could anyone tell me what am I missing? Are there any other ways to do this?
Thank you!
let e, x, d = 0;
let b = prompt("Enter a number");
x=b;
while (x > 0) {
e = x % 10;
x = parseInt(x/10);
d = d + (e*e*e);
}
if (b==d)
alert("given number is an armstrong number");
else
alert("given number is not an armstrong number");
<!DOCTYPE HTML>
<html>
<head>
<title>Armstrong</title>
</head>
<body>
</body>
</html>
I think the way you compute the result is wrong. According to Wikipedia, an Armstrong number, also called narcissistic number, has the following property:
[An Armstrong number] is a number that is the sum of its own digits each raised to the power of the number of digits.
You can compute it like this:
var number = prompt("Enter a number");
var numberOfDigits = number.length;
var sum = 0;
for (i = 0; i < numberOfDigits; i++) {
sum += Math.pow(number.charAt(i), numberOfDigits);
}
if (sum == number) {
alert("The entered number is an Armstrong number.");
} else {
alert("The entered number is not an Armstrong number.");
}
You can try this method, very easy to understand.
const armstrongNumber = (num) => {
const toArray = num.toString().split('').map(Number);
const newNum = toArray.map(a => {return a**3}).reduce((a, b) => a + b);
if(newNum == num){
console.log('This is an armstrong number');
}else{
console.log('This is not an armstrong number');
}
}
armstrongNumber(370);
//This is an armstrong number
Here is the solution to check Armstrong number without using Math Object.
function armstrongNum(number) {
const numberArr = String(number).split('');
const power = numberArr.length;
let TotalSum = numberArr.reduce((acc, cur) => {
return acc + (function(cur,power){
let curNum = Number(cur);
let product = 1;
while(power > 0) {
product *= curNum;
power --;
}
return product;
}(cur,power))
}, 0)
if (TotalSum === number) {
return true
}
return false
}
armstrongNum(153);
Here is an example of functional code for Armstrong Numbers.
<script>
function execute() {
var num1 = document.getElementById("Number1").value;
var num2 = document.getElementById("Number2").value;
var num3 = document.getElementById("Number3").value;
var concatNum = num1 + num2 + num3;
var num1Sqrt = num1 * num1 * num1;
var num2Sqrt = num2 * num2 * num2;
var num3Sqrt = num3 * num3 * num3;
if (num1Sqrt + num2Sqrt + num3Sqrt == concatNum) {
Answer.value = "The three integers you entered are Armstrong numbers.";
}
if (num1Sqrt + num2Sqrt + num3Sqrt != concatNum) {
Answer.value = "The three integers you entered are not Armstrong numbers.";
}
}
</script>
You first set your variables to what is entered, you then concatenate the string with the three integers.
You then square the three integers and set each value to a variable. You then have a basic check for equality, if the three squared values add up to your concatenated string then you have an Armstrong number.
This is how i solved mine:
function armstrong(num) {
var digits = num.toString().split('')
var realDigits = num
var a = 0
for (let i = 0; i < digits.length; i++){
digits[i] = Math.pow(digits[i], digits.length)
a += digits[i]
}
if (a == realDigits) {
console.log("Number is armstrong")
} else if (a != realDigits) {
console.log("Number is not armstrong")
}
}
armstrong(371)
//feel free to pass any value here
You can copy/paste and run this code at https://www.typescriptlang.org/play/
I hope this helps someone.
This works as well..
function isArmstrong (n) {
const res = parseInt(n, 10) === String(n)
.split('')
.reduce((sum, n) => parseInt(sum, 10) + n ** 3, 0);
console.log(n, 'is', res, 'Armstrong number')
return res
}
isArmstrong(153)
Here is another way to solve it.
let c = 153
let sum = 0;
let d = c.toString().split('');
console.log(d)
for(let i = 0; i<d.length; i++) {
sum = sum + Math.pow(d[i], 3)
}
if(sum == c) {
console.log("armstrong")
}
else {
console.log("not a armstrong")
}
Correct way to find Armstrong
var e, x, d = 0, size;
var b = prompt("Enter a number");
b=parseInt(b);
x=b;
size = x.toString().length;
while (x > 0) {
e = x % 10;
d = d + Math.pow(e,size);
x = parseInt(x/10);
}
//This is I solved without function
let num = prompt();
let num1 = num;
let sum = 0;
while(num > 0){
rem = num % 10;
sum = sum + Math.pow(rem, num1.length);
num = parseInt (num /10);
}
if (sum == num1) console.log("Armstrong");
else console.log("not Armstrong");
number is an Armstrong number or not.
let inputvalue=371
let spiltValue=inputvalue.toString().split('')
let output=0
spiltValue.map((item)=>output+=item**spiltValue.length)
alert(`${inputvalue} ${inputvalue==output? "is armstrong number" : "is not armstrong number"}`);
In order to get a Narcissistic/Armstrong number, you need to take the
length of the number as n for taking the power for summing the
value.
Here's another solution that works with an input >= 3 digits
(With Math.pow() each character is added as a number to the power of the array size)
const isArmstrongNumber = (n) => {
//converting to an array of digits and getting the array length
const arr = [...`${n}`].map(Number);
let power = arr.length;
const newNum = arr
.map((a) => {
return Math.pow(parseInt(a), power);
})
.reduce((a, b) => a + b);
return newNum == n;
};
console.log("Is it Armstrong? " + isArmstrongNumber(370));
console.log("Is it Armstrong? " + isArmstrongNumber(123));
console.log("Is it Armstrong? " + isArmstrongNumber(1634));
You can try for This, May this help for you:
<!DOCTYPE HTML>
<html>
<head>
<title>Armstrong</title>
</head>
<body>
</body>
</html>
<script>
var z,e,x,d=0;
var b=prompt("Enter a number");
x=parseInt(b);
while(x>0) //Here is the mistake
{
e=x%10;
x=parseInt(x/10);
d=d+(e*e*e);
console.log("d: "+d+" e: "+e);
}
if(parseInt(b)==d){
alert("given no is amstrong number");
}
else {
alert("given no is not an amstrong number");
}
</script>
Related
Here's the question:
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).
For example, take 153 (3 digits), which is narcisstic:
1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
Your code must return true or false (not 'true' and 'false') depending upon whether the given number is a Narcissistic number in base 10.
My Code is:
function narcissistic(value) {
let vLen = value.length;
let sum = 0;
for (let i = 0; i < vLen; i++) {
sum += Math.pow(value[i], vLen);
}
if (sum == value) {
return true;
} else {
return false;
}
}
But I'm getting errors. What should I do?
Numbers don't have .length, convert to string first
vLen[i], you cant treat a number as array, again, convert to string to use that syntax.
The return can be simplefied to return (sum === value);
function narcissistic(value) {
let sVal = value.toString();
let vLen = sVal.length;
let sum = 0;
for (let i = 0; i < vLen; i++) {
sum += Math.pow(sVal[i], vLen);
}
return (sum === value);
}
console.log(narcissistic(153));
console.log(narcissistic(111));
Well... There are several things wrong with this code, but I think there is mostly a problem with the types of your input.
I'll show you how you can cast the types of your input to make sure you work with the types you need:
Also... You should try to avoid using the == operator and try to use === instead (same goes for != and !==), because the == and != don't try to match the types, resulting in sometimes unpredictable results
function narcissistic(value) {
valueStr = String(value);
let vLen = valueStr.length;
let sum = 0;
for (let i = 0; i < vLen; i++) {
sum += Number(valueStr[i]) ** vLen;
}
if (sum === value) {
return true;
} else {
return false;
}
}
if(narcissistic(153)) {
console.log("narcissistic(153) is true!") // expected value: true
}
All the first 9 digits from 1 to 9 is Narcissistic number as there length is 1 and there addition is always same.
So, first we are checking weather the number is greater than 9 or not.
if(num>9) =>false than it's a narcissistic number.
-if(num>9) =>true than we have to split number into digits for that I have used x = num.toString().split('');. Which is first converting number to String and than using split() function to split it.
Than , we are looping through each digit and digitsSum += Math.pow(Number(digit), x.length); adding the power of digit to const isNarcissistic = (num) => { let x = 0; let digitsSum.
at the end, we are comparing both num & digitsSum if there are matched than number is narcissistic else not.
const isNarcissistic = (num) => {
let x = 0;
let digitsSum = 0;
if (num > 9) {
x = num.toString().split('');
x.forEach(digit => {
digitsSum += Math.pow(Number(digit), x.length);
});
if (digitsSum == num) {
return true;
} else {
return false;
}
} else {
return true;
}
}
console.log(isNarcissistic(153));
console.log(isNarcissistic(1634));
console.log(isNarcissistic(1433));
console.log(isNarcissistic(342));
while (a) {
b.push(a % 10);
a = Math.floor(a / 10);
if (b == 7) {
n = n + 1;
}
console.log("<br><br>number of 7's:" + n);
}
This is what I have come up with. The output is one of the numbers has seven; if not, then zero. I want the program to count the number of times seven appears in a number.
You can convert the number to a string, and then count how many times a character = 7:
let n = 7326577
let cnt = 0;
let strN = '' + n;
for(let c of strN)
if(c == '7')
cnt ++
console.log('Number of 7\'s in number: ' + cnt)
Following you approach you need to store the last digit to a different variable and use that for checking if it is a 7
var a = 709728457;
var b = [];
var n = 0;
while (a) {
const lastDigit = a % 10;
b.push(lastDigit); // if you still need to store all digits
a = Math.floor(a / 10);
if (lastDigit == 7) {
n = n + 1;
}
}
console.log("number of 7's:" + n);
var a = 7686774737
var no = String(a).split('').filter(e=>e==7).length;
console.log(no)
I am completely new to Javascript and trying to solve a simple problem now for more than two weeks and still not getting it(please help).
TASK ::::
Read a 4 digit Number e.g. 5678
Write a function
Split/separate the numbers and than build (5678, 567, 56, 5), than check if the numbers(5678, 567, 56, 5) are Prime numbers.
Give in Console/Result if 5678 a prime number or not, 567 a prime number or not and so on.
Check "if all numbers are Prime" than show result "All prime" if not show result "Not all prime".
Trying to solve the problem with (if else) but not really getting it, because i know very less about Javascript (arrays, string, split, slice) yet.
please help me understand. Thanks.
var a = 123456789;
var b = a.toString().length; //<<--->> ANTWORT: 9
document.write('ANTWORT: ',a );
for (i=0; i<b; i++) {
var x = a.toString().slice(0, -i);
document.write(x, ",");
}
function isPrime{
for(var i = 2; i < a; i++);
if(num % i === 0) return false;
return num > 1;
}
//integer is a string at the moment
integer = prompt("Enter a integer: ");
//initialize array for dictionary
dictArray = [];
stuff = document.getElementById("stuff");
//loop through all values of the string
for (var i = integer.length; i > 0; i--)
{
//take a substring from 0 to the ith char and turn it into an int
num = parseInt(integer.substring(0, i));
//add a dictionary to the array the tells what the number is
//and if it was prime or not as a bool
dictArray.push({"num": num, "prime": isprime(num)});
(dictArray[integer.length - i]["prime"]) ? stuff.innerHTML += "<br>" + num + " is prime." : stuff.innerHTML += "<br>" + num + " is not prime.";
}
function isprime(num)
{
if (num <= 3) return num >= 1;
if ((num % 2 === 0) || (num % 3 === 0)) return false;
let count = 5;
while (Math.pow(count, 2) <= num) {
if (num % count === 0 || num % (count + 2) === 0) return false;
count += 6;
}
return true;
}
//print the array
(dictArray.find(x => !x.prime) == undefined) ? stuff.innerHTML += "<br>All prime!" : stuff.innerHTML += "<br>Not all prime!";
//console.log(dictArray);
<div id="stuff">
</div>
Given Problem:
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
My code:
function sumDigits(num) {
return num.toString().split("").reduce(function(a, b){
return parseInt(a) + parseInt(b);
});
}
My code solves the problem for positive integers. Any hints on how should I go about solving the problem for negative integers? Please and thanks.
Edit: And what if the given number is 0? Is it acceptable to add an if statement to return 0 in such cases?
Check to see if the first character is a -. If so, b is your first numeral and should be negative:
function sumDigits(num) {
return num.toString().split("").reduce(function(a, b){
if (a == '-') {
return -parseInt(b);
} else {
return parseInt(a) + parseInt(b);
}
});
}
You could use String#match instead of String#split for a new array.
function sumDigits(num) {
return num.toString().match(/-?\d/g).reduce(function(a, b) {
return +a + +b;
});
}
console.log(sumDigits(1148)); // 14
console.log(sumDigits(-316)); // 4
Somebody who is looking for a solution without reduce functions etc. can take this approach.
function sumDigits(num) {
var val = 0, remainder = 0;
var offset = false;
if (num <0) {
offset = true;
num = num * -1;
}
while (num) {
remainder = num % 10;
val += remainder;
num = (num - remainder) / 10;
}
if (offset) {
val -= 2 * remainder;//If the number was negative, subtract last
//left digit twice
}
return val;
}
var output = sumDigits(-348);
console.log(output);
output = sumDigits(348);
console.log(output);
output = sumDigits(1);
console.log(output);
//Maybe this help: // consider if num is negative:
function sumDigits(num){
let negativeNum = false;
if(num < 0){
num = Math.abs(num);
negativeNum = true;
}
let sum = 0;
let stringNum = num.toString()
for (let i = 0; i < stringNum.length; i++){
sum += Number(stringNum[i]);
}
if(negativeNum){
return sum - (Number(stringNum[0]) * 2);
// stringNum[0] has the "-" sign so deduct twice since we added once
} else {
return sum;
}
}
Following are the rules:
Generate random numbers of length N.
Not more than two consecutive digits in a number should be the same.
I written code, but even though 2 same consecutive digits in a number are allowed, it's not working. All unique random numbers are generated.
I keep one temporary variable, which stores the previous number generated, if it matches the present generate number, then discard and generate again.
while (rnum.length<=7)
{
gennum = randomNumericChar();
if(rnum.length==0) {
rnum = rnum.concat(gennum);
prevnum = gennum;
} else if(gennum!=prevnum) {
rnum = rnum.concat(gennum);
prevnum = gennum;
}
}
return rnum;
FOund solution:
Hi, i got the solution. ` var rnum = "" ;
var random;
while(rnum.length<=7)
{
random= generaterandom();
if(rnum.length<2)
{
rnum = rnum.concat(random);
}else
{
//check whether previous two numbers are same, if not then append generated random number
if(!(random==rnum.charAt(rnum.length-1) && random==rnum.charAt(rnum.length-2)))
{
rnum = rnum.concat(random);
}
}
}`
This might be your solution:
function randomNumericChar(lastNumber) {
var num = Math.floor((Math.random() * 10) + 1);
if (lastNumber !== null && num === lastNumber) {
return randomNumericChar(lastNumber);
} else {
return num;
}
}
function createNumber(n) {
var randomNumber = '';
var lastChar = null;
while (randomNumber.length < n) {
var num = randomNumericChar(lastChar);
if (((randomNumber.length + 1) % 2) === 1) {
lastChar = num;
}
randomNumber += num;
}
return randomNumber;
}
var randomNumber = createNumber(10);
Edit: forgot about the fact that there might be 1 consecutive number.