How to a count a specific digit in a number with javascript - javascript

I am trying to write a block of code which will separate digits (with modulus operator) in a number first and count how many digit "6" are there in the number.
I tried so many things but I think I have logic problem with the way I think.
output = [];
var count = 0;
while (a > 0){
output.push(a % 10);
a = Math.floor(a/10);
if(a == 6){
count++;
}
}
When I run this code on Safari, It shows the entered number as it is, but it shows "0" for the variable count.

Math.floor(a/10) doesn't give the current digit. a % 10 gives the current digit.
You have check if the current digit a % 10 is 6.
Live Example:
let output = [];
let count = 0;
let a = 1667;
while (a > 0) {
let digit = a % 10;
output.push(digit);
if (digit == 6) {
count++;
}
a = Math.floor(a / 10);
}
console.log(count);

You know the last digit, so you can subtract it and divide with 10, instead of using Math.floor.
let number = 1626364656; // has 5 sixes
let sixesCount = 0;
while (number > 0) {
const digit = number % 10;
if (digit === 6) {
sixesCount++;
}
number = (number - digit) / 10;
}
console.log('Found', sixesCount, 'sixes.'); // "Found 5 sixes."

Related

How to add suffixes to an amount of money in javascript

I have a game where you earn money, and it is very easy to get rich. I want to make it so that if you get money more than a million, instead of showing 1234567, it shows 1.2 million. The process I am trying to go for if the number is more than a million is:
1: get the first two digits
2: remove the first two digits
3: store the remaining digits into a list
4: divide the length of the list by 3
5: get that value in the list of suffixes - 1 (because lists start at 0, not 1)
I can make the list of suffixes, I just need help on how to make this process.
This might be a good starting place for you. Let me know if it helps.
const $ = s => [...document.querySelectorAll(s)];
function formatNumber(n) {
if (n > 10**9 - 1) {
return (n / 10**9).toFixed(2) + "b"
} else if (n > 10**6 - 1) {
return (n / 10**6).toFixed(2) + "m"
} else {
return n
}
}
$("button")[0]
.addEventListener("click", e => {
const userInput = $("input")[0].value;
const formattedNumber = formatNumber(userInput);
$("#display")[0].innerText = formattedNumber;
});
body {
font-size: 2em;
}
<input type="number">
<button>Go</button>
<div id="display">output</div>
Here's an efficient approach that doesn't require any parsing - just simple string manipulation:
Get the digits greater before the 6 digit mark by subtracting the length of the string by 6
For the digit immediately after the 6 digit mark, you can use charAt and get the character at the index of the length of the string minus 6
Result:
const num = "13356789";
function wordify(number) {
if (number.length > 6) {
const start = num.substring(0, number.length - 6);
const second = num.charAt(number.length - 6);
return `${start}.${second} million`;
}
}
console.log(wordify(num));
Try it yourself with custom numbers:
function wordify(number) {
if (number.length > 6) {
const start = number.substring(0, number.length - 6);
const second = number.charAt(number.length - 6);
return `${start}.${second} million`;
}else{
return `number must have at least 6 digits`;
}
}
num.addEventListener('input', () => {
result.innerHTML = wordify(num.value);
});
Enter a number: <input id="num" type="number"><br/><br/> Result: <span id="result"></span>
Handling all cases (thousands, millions and billions):
let money = 1234567;
let strMoney = String(money);
if(strMoney.length >= 7 && strMoney.length <= 9) {
console.log(Math.round(money/ 1000000 * 100)/100, 'million')
}else if(strMoney.length > 9) {
console.log(Math.round(money/ 1000000000 * 100)/100, 'billion')
}else if(strMoney.length <= 6 && strMoney.length >= 4){
console.log(Math.round(money/ 1000 * 100)/100, 'thousand')
}else {
console.log(money)
}

how to make a script to print out all prime numbers in js

I want to know how I can improve my code by helping it find out what number is prime and what is not. I was thinking that I would divide a number by a number and then if it is a decimal number then it is prime,
I want it to have a loop to check every number 1 to 100 and see if it is a prime number
This is what I have so far:
for(let i = 1; i <= 100; i++) {
if(i == 1) {
}else if(i == 2) {
console.log(`${i} is a prime number`);
}else if(i >= 3){
x = i / 2;
tf = Number.isInteger(x);
if(tf == false && i >= 3) {
console.log(`${i} is a prime number`);
}
}
}
and so far it outputs 1 2 and all the odd numbers.
Create a function to test whether a number is prime or not (divisible only by 1 and itself). Then call this function inside the loop on each number.
function isPrimeNumber(no) {
if (no < 2) {
return false;
}
for (let i = 2; i < no; i++) {
if (no % i == 0) {
return false;
}
}
return true;
}
for (let i = 1; i <= 100; i++) {
if (isPrimeNumber(i)) {
console.log(i);
}
}
var numbers = new Array(101).fill(0).map((it, index) => index);
var halfWay = Math.floor(numbers.length / 2);
for (let i = 2; i <= halfWay; i++) {
if (!numbers[i]) continue;
for (let j = 2; j * i < numbers.length; j++) {
console.log(`${i} * ${j} = ${i * j}`);
numbers[j * i] = null;
}
}
console.log(numbers.filter(it => it));
Here is an attempt to mathematically find numbers between 1-100 that are primes.
Fill an array of numbers 0-100
For every number (starting at 2), multiply it by itself and all numbers after it, up to half of the array
For every computed number, remore it from the array, as it is not a prime
At the end, filter out all numbers that are null
As Taplar stated primes are numbers that only divide by the number itself and 1.
As far as improving your code. I would say you want to eliminate as many possible numbers with the fewest questions.
An example would be is the number even and not 2 if so it is not prime? The interesting part of this question you eliminate dividing by all even numbers as well. This instantly answers half of all possible numbers and halves the seek time with the ones you need to lookup.
So what would this look like?
function isPrime(num) {
// Check it the number is 1 or 2
if (num === 1 || num === 2) {
return true
}
// Check if the number is even
else if (num % 2 === 0) {
return false;
}
// Look it up
else {
// Skip 1 and 2 and start with 3 and skip all even numbers as they have already been checked
for (let i = 3; i <= num/2; i+=2) {
// If it divides correctly then it is not Prime
if (num % i === 0) {
return false
}
}
// Found no numbers that divide evenly it is Prime
return true
}
}
console.log('1:', isPrime(1))
console.log('2:', isPrime(2))
console.log('3:', isPrime(3))
console.log('4:', isPrime(4))
console.log('11:', isPrime(11))
console.log('12:', isPrime(12))
console.log('97:', isPrime(97))
console.log('99:', isPrime(99))
console.log('65727:', isPrime(65727))
console.log('65729:', isPrime(65729))

Display number series with modulo in JavaScript

I'm currently trying to display number series (for 2, 3, 4, 5, 6 and 7) in JavaScript. I was looking for the smallest number (x), which results in modulo = 1, if divided by 2, 3, 4, 5 and 6. If the same number (x) is divided by 7, id should result in modulo = 0. I'm not quite sure, if I'm explaining it correct. It should be like this: x % 2 = 1, x % 3 = 1, x % 4 = 1, x % 5 = 1, x % 6 = 1, x % 7 = 0.
The result is 301. My code looks like this and it works fine:
var seven = 7;
var six;
var five;
var four;
var three;
var two;
while (six != 1 || five != 1|| four != 1|| three != 1|| two != 1)
{six = seven % 6;
five = seven % 5;
four = seven % 4;
three = seven % 3;
two = seven % 2;
console.log(seven);
seven += 7;}
It displays all the numbers in the seven-series, until 301. Now, I wanted some more while-loops for the other numbers (2-6), that work the same why and show all the different numbers/steps in each series, until 301. I'm new to JavaScript and I just don't get it. I tried to modify my code, so that it should work with the other number series, but it doesn't. Or is there any other (maybe a better) way to do this? With some nested loops/functions? It only should be possible to display every number in each number series, but not all at the same time (in the end, there should be buttons, which show (by clicking them) the different number series with all the numbers/steps until 301). Thank you soso much!
When doing this you should probably use a loop to simplify your life.
Start x at 0 and iterate to (for example) 100.000.
For every iteration, check to see if x % 2 / 3 / 4 / 5 / 6 is equal to 0. Then check to see if x % 7 === 1. If both these conditions are true, log the value and break the for loop.
The smallest value that answers this seems to be 120.
const numbers = [2,3,4,5,6]
const special = 7;
for(let x = 0; x < 100000; x++){
const isModulo0ForAllNumbers = numbers.every(n => (x % n) === 0);
const isModulo1ForSpecial = (x % special) === 1;
if(isModulo0ForAllNumbers && isModulo1ForSpecial){
console.log(`Smallest number found: ${x}`);
break;
}
}
Sometimes this is not possible to find such a number and you'll get infinite loop with unexpected behavior. This is a possible approach (see the comments inside):
// first define the greatest common divisor
// for two numbers - we'll need that later
let gcd = function(a, b) {
// classic 'Euclidean' method with recursion
if(a == 0) {
return b;
}
if(a > b) {
return gcd(b, a);
}
return gcd(b % a, a);
}
// define your series
let series = [2,3,4,5,6,7];
// now you need least common multiple for all numbers
// except for the last one
lcm = series[0];
for (let i = 1; i < series.length - 1; i++) {
lcm *= series[i] / gcd(lcm, series[i])
}
// the last number from series
let last = series[series.length - 1];
// exercise: you can research or think for smarter solution
// I will just loop until we get the result
if(gcd(lcm, last) == 1) {
let r = lcm + 1;
while(r % last) {
r += lcm;
}
console.log('number found: ', r);
} else {
// not possible
console.log('impossible to find the number');
}
You could take an array of values for the modulo calculation and use a function for getting a check of a value.
const f = x => [2, 3, 4, 5, 6].every(v => x % v === 1) && x % 7 === 0;
var value = 0;
while (!f(value)) value += 7;
console.log(value);

Difficulty in constructing Luhn's algorithm

I want to construct Luhn's algorithm which is usually used to validate credit card numbers. Luhn's algorithm works like this:
Isolate every digit, starting from the right moving left, doubling every second one. If the doubled value is greater than 9, subtract 9 from it.
Sum all the transformed digits.
The original number valid according to Luhn's algorithm if and only if the sum ends in a 0.
function isValid(number) {
return LuhnDigitSum(number) % 10 === 0;
}
function LuhnDigitSum(number) {
let sum = 0;
let num_str = number.toString();
let reversed_num = num_str.split("").reverse().join("");
for (let i = 0; i < reversed_num.length; i++) {
let digit = parseInt(reversed_num[i]);
if (i % 2 !== 0 && (digit * 2) <= 9) {
digit = digit * 2;
sum += digit;
}
if (i % 2 !== 0 && (digit * 2) > 9) {
digit = (digit * 2) - 9;
sum += digit;
}
if (i % 2 === 0) {
sum += digit;
}
}
return sum;
}
When i run the code, the card numbers appeared to be invalid when they are supposed to be valid, and adding to that, the sum value were incorrect.
Your help is much appreciated. Thanks!!

How to get 2 random numbers divisible by each other?

I'm generating 2 random numbers:
1) The first number must be random from 1 to 30
2) The second number must be random from 1 to 10
I'm simply trying to have the first number divisible by the second number or vice-versa, and finally, alert the result. My question is how to get the result of the division of 2 random numbers? Can anyone point me in the right direction? Thanks a lot in advance!.
Note: the first number must be divisible by the second number.
Here's my code:
var arr = [];
for (var i = 0; i < 2; i++) {
do {
var firstRandomNumber = Math.floor(Math.random()*30) + 1;
var secondRandomNumber = Math.floor(Math.random()*10) + 1;
if(firstRandomNumber % secondRandomNumber === 0){
correctResult = result;
arr.push(correctResult);
}
} while ((firstRandomNumber % secondRandomNumber === 0));
}
console.log(arr);
I would suggest a more functional approach: create a function that creates two random numbers, and returns them if one is divisible by the other. Then, just call that function until you get a truthy result:
function tryGetDivisible() {
var firstRandomNumber = Math.floor(Math.random() * 30) + 1;
var secondRandomNumber = Math.floor(Math.random() * 10) + 1;
if (firstRandomNumber % secondRandomNumber === 0) {
console.log(firstRandomNumber, secondRandomNumber);
return firstRandomNumber / secondRandomNumber;
}
}
let result;
while (!result) result = tryGetDivisible();
const arr = [result];
console.log(arr);
Few things:
Your while loop should be looping until firstRandomNumber % secondRandomNumber === 0, so you want to just keep looping while it's not true.
result isn't set anywhere, so I added the result in the array
The if(firstRandomNumber % secondRandomNumber === 0){ is redundant. When the do/while loop completes, it will have the do numbers that matched. Simply move the arr.push() outside that loop.
var arr = [];
for (var i = 0; i < 2; i++) {
do {
var firstRandomNumber = Math.floor(Math.random()*30) + 1;
var secondRandomNumber = Math.floor(Math.random()*10) + 1;
} while ((firstRandomNumber % secondRandomNumber !== 0));
console.log('first', firstRandomNumber, 'second', secondRandomNumber);
arr.push(firstRandomNumber / secondRandomNumber);
}
console.log(arr);
A much simpler approach is to get the first random number, and then try getting the second random number until they are divisible. So here will be the code:
var firstRandomNumber = Math.floor(Math.random()*30) + 1;
while (firstRandomNumber % secondRandomNumber !== 0) {
var secondRandomNumber = Math.floor(Math.random()*10) + 1;
}
console.log(firstRandomNumber + "," + secondRandomNumber);
Since the first must be divisible by the second, my approach would be:
Generate the second number.
Determine the maximum multiple of the second number that is no more than 30 (e.g., Math.floor(30/firstNumber)).
Select a multiple at random and use that as the first number. You simply need to select a random number between 1 and the largest allowed multiplier (inclusive).
This way, there's no need to do a generate-and-test loop, which could go on an unbounded number of times before a successful pair is generated.
If you want to avoid the while loop, you can pick the first number, then assemble the possible second numbers in an array. Then randomly pick one of these:
let first = Math.floor(Math.random() * 10) + 1
// all possible divisible numbers
let factors = Array.from({length: 30}, (_, i) => i + 1)
.filter(i => first % i === 0 || i % first === 0)
//pick one
let second = factors[Math.floor(Math.random() * factors.length)]
console.log(first, second)

Categories

Resources