I have a question, my code worked but in the case that it's a bigger number and I don't have an idea of where to put the limit in my i position... How can I optimize this code, so I don't need to calculate the limit and not put so many zeros in my i? Or there's no way and this is as it should be?
function prob5(){
for(var i =1;i<10000000000;i++){
if((i%1)==0 && (i%2)==0 && (i%3)==0 && (i%4)==0 && (i%5)==0 && (i%6)==0 && (i%7)==0 && (i%8)==0 && (i%9)==0 && (i%10)==0 && (i%11)==0 && (i%12)==0 && (i%13)==0 && (i%14)==0 && (i%15)==0 && (i%16)==0 && (i%17)==0 && (i%18)==0 && (i%19)==0 && (i%20)==0) {
break;
}
}
console.log(i);
}
function getLowestNumDivisibleByAllUpTo(limit) {
const numMax = factorial(limit);
for (let num = 1; num < numMax; num++) {
let divisibleByAll = true;
for (let divisor = 2; divisor <= limit; divisor++) {
if (num % divisor !== 0) {
divisibleByAll = false;
break;
}
}
if (divisibleByAll) {
return num;
}
}
}
function factorial(n) {
if (n < 2) return 1;
return n * factorial(n - 1);
}
console.log(getLowestNumDivisibleByAllUpTo(20));
/*
the number you are looking for is called the least common multiple (lcm)
to find the least common multiple of all numbers in an array:
compute the lcm of the first two, then the lcm of the fist two with the third and so on
lcm(2,3)=6, lcm(6,4)=12, lcm(12,5)=60, etc
the following is much more efficient because it doesn't search billions of numbers
to check if they are divisible by 2 and 3 and 4 and ... 20
it just applies the same function, lcm, 18 times
*/
const limit = 20;
const divisors = [...Array(limit - 1)].map((v, i) => 2 + i);
// greatest common divisor of two numbers
const gcd = (a, b) => b ? gcd(b, a % b) : Math.abs(a);
// least common multiple of two numbers
const lcm = (a, b) => a * b / gcd(a, b);
// least common multiple of all numbers in an array
const lcma = array => array.reduce(lcm);
console.log(lcma(divisors));
Thinking it would be like
for number from range x,y
if number in ones or number in hundreds
print
else
??? I don't know what command to do the if statement.
You may try using the modulus operator here:
for (i=100; i <= 200; ++i) {
if (i % 10 == 2 || Math.floor(i / 10) % 10 == 3) {
console.log(i);
}
else {
// turned this off for demo purposes
// console.log("???");
}
}
for (let i = 100; i <= 200; i++) {
if (i % 10 === 2 || (i / 10) % 10 === 3) {
// do something
} else {
console.log('???')
}
}
You could store the tensDigit and onesDigit in variables and then check them in the if statement for better readabilty:
for (let num = 100; num <= 200; num++) {
const tensDigit = Math.floor((num % 100) / 10);
const onesDigit = num % 10;
if (tensDigit === 3 || onesDigit === 2) {
console.log(num);
}
}
your question is super ambiguous, please be more specific. That being said this function should do what you are asking.
function printIfDigitIsInPlace(INPUT, DIGIT, PLACE) {
const arr = Array.from(INPUT.toString());
if (arr[PLACE] === DIGIT.toString()) console.log(INPUT);
}
I was trying to solve this problem on a leet code called Rotate digits.
This is the working solution of the problem in Javascript :
var IsGood = function(n){
let result = false;
while(n > 0){
let digit = n % 10; // 2 % 10
// ignore 0, 1, 8; by themselves, no change
if( (digit === 3) || (digit === 4) || (digit === 7) ) return false;
if( (digit === 2) || (digit === 5) || (digit === 6) || (digit === 9) ) result = true;
n /= 10;
}
return result;
}
var rotatedDigits = function(N) {
let count = 0;
for(let i = 1; i <= N; i++){
if(IsGood(i)) count++;
}
return count;
}
My question inside the IsGood function why are we taking n % 10 and then dividing n /=10. I have seen this implementation in almost all solutions to this problem. Can someone please explain the logic behind this?
Take the number 123
The remainder of that number when divided by 10 is 3 (123 % 10) = 3.
So n%10 is giving you the last digit of the number
If you want to test the next digit in the number you have to remove the 3. The way to do that is to divide by 10 and only take the integer part (12.3 lose the .3 part) which you get by 123 / 10
You can keep doing that until you get to a number less than 10 which must be the final digit! this algorithm is a way to examine each digit in a number using math rather than string manipulation
123 % 10 = 3 first digit
123 / 10 = 12
12 % 10 = 2 next digit
12 / 10 = 1
1 < 10 so final digit
I'm trying to complete an algorithm challenge to find the largest prime factor of 600851475143. I'm not necessarily asking for the answer. Just trying to figure out why this code isn't working. Why does it return 'undefined' instead of a number?
let isPrime = n => {
let div = n - 1;
while (div > 1) {
if (n % div == 0) return false;
div--;
}
return true;
};
let primeFactor = x => {
for (let i = Math.floor(x / 2); i > 1; i--) {
if (x % i == 0 && isPrime(i) == true) {
return i;
}
}
};
console.log(primeFactor(35)); // 7
console.log(primeFactor(13195)); // 29
console.log(primeFactor(600851475143)); // undefined
The problem is not your algorithm it is perfectly valid, check the below slightly modified algorithm, all I've done is replaced your starting point Math.floor(x/2) with a parameter that you can choose:
let isPrime = n => {
let div = n - 1;
while (div > 1) {
if (n % div == 0) return false;
div--;
}
return true;
};
function primeFactor(x, n){
for (let i = n; i > 1; i--) {
if (x % i == 0 && isPrime(i) == true) {
return i;
}
}
}
console.log(primeFactor(35, 35));
console.log(primeFactor(13195, 13195));
console.log(primeFactor(600851475143, 100000))
Using the above you'll get an answer that proves your implementation works, but the loop is too big to do the entire thing(i.e. from Math.floor(600851475143/2)). Say your computer can do 500million loops per second, going through every one from 300,425,737,571 down to 1 would take 167 hours, even at 5 billion loops per second it would take 16 and a half hours. Your method is extremely inefficient but will return the correct answer. The reason you're not getting an answer on JSBin is more likely to do with browser/service limitations.
Spoilers on more efficient solution below
The following implementation uses a prime sieve(Sieve of Eratosthenes) in order to generate any list of primes requested and then checks if they fully factor into the given number, as long as you use a large enough list of primes, this will work exactly as intended. it should be noted that because it generates a large list of primes it can take some time if ran incorrectly, a single list of primes should be generated and used for all calls below, and the cached list of primes will pay off eventually by having to perform less calculations later on:
function genPrimes(n){
primes = new Uint32Array(n+1);
primes.fill(1)
for(var i = 2; i < Math.sqrt(n); i++){
if(primes[i]){
for(var j = 2*i; j < n; j+=i){
primes[j] = 0;
}
}
}
primeVals = []
for(var i = 2; i < primes.length; i++){
if(primes[i]){
primeVals.push(i);
}
}
return primeVals;
}
function primeFactor(x, primes){
var c = x < primes.length ? x : primes.length
for (var i = c; i > 1; i--) {
if(x % primes[i] == 0){
return primes[i];
}
}
}
primes = genPrimes(15487457);
console.log(primeFactor(35, primes));
console.log(primeFactor(13195, primes));
console.log(primeFactor(600851475143, primes));
console.log(primeFactor(30974914,primes));
let primeFactor = x => {
if (x === 1 || x === 2) {
return x;
}
while (x % 2 === 0) {
x /= 2;
}
if (x === 1) {
return 2;
}
let max = 0;
for (let i = 3; i <= Math.sqrt(x); i += 2) {
while (x % i === 0) {
x /= i;
max = Math.max(i, max);
}
}
if (x > 2) {
max = Math.max(x, max);
}
return max;
};
console.log(primeFactor(35));
console.log(primeFactor(13195));
console.log(primeFactor(27));
console.log(primeFactor(1024));
console.log(primeFactor(30974914));
console.log(primeFactor(600851475143));
Optimizations
Dividing the number by 2 until it's odd since no even number is prime.
The iteration increment is 2 rather than 1 to skip all even numbers.
The iteration stops at sqrt(x). The explanation for that is here.
I have a number assigned to a variable, like that:
var myVar = 1234;
Now I want to get the second digit (2 in this case) from that number without converting it to a string first. Is that possible?
So you want to get the second digit from the decimal writing of a number.
The simplest and most logical solution is to convert it to a string :
var digit = (''+myVar)[1];
or
var digit = myVar.toString()[1];
If you don't want to do it the easy way, or if you want a more efficient solution, you can do that :
var l = Math.pow(10, Math.floor(Math.log(myVar)/Math.log(10))-1);
var b = Math.floor(myVar/l);
var digit = b-Math.floor(b/10)*10;
Demonstration
For people interested in performances, I made a jsperf. For random numbers using the log as I do is by far the fastest solution.
1st digit of number from right → number % 10 = Math.floor((number / 1) % 10)
1234 % 10; // 4
Math.floor((1234 / 1) % 10); // 4
2nd digit of number from right → Math.floor((number / 10) % 10)
Math.floor((1234 / 10) % 10); // 3
3rd digit of number from right → Math.floor((number / 100) % 10)
Math.floor((1234 / 100) % 10); // 2
nth digit of number from right → Math.floor((number / 10^n-1) % 10)
function getDigit(number, n) {
return Math.floor((number / Math.pow(10, n - 1)) % 10);
}
number of digits in a number → Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1 Credit to: https://stackoverflow.com/a/28203456/6917157
function getDigitCount(number) {
return Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1;
}
nth digit of number from left or right
function getDigit(number, n, fromLeft) {
const location = fromLeft ? getDigitCount(number) + 1 - n : n;
return Math.floor((number / Math.pow(10, location - 1)) % 10);
}
Get rid of the trailing digits by dividing the number with 10 till the number is less than 100, in a loop. Then perform a modulo with 10 to get the second digit.
if (x > 9) {
while (x > 99) {
x = (x / 10) | 0; // Use bitwise '|' operator to force integer result.
}
secondDigit = x % 10;
}
else {
// Handle the cases where x has only one digit.
}
A "number" is one thing.
The representation of that number (e.g. the base-10 string "1234") is another thing.
If you want a particular digit in a decimal string ... then your best bet is to get it from a string :)
Q: You're aware that there are pitfalls with integer arithmetic in Javascript, correct?
Q: Why is it so important to not use a string? Is this a homework assignment? An interview question?
You know, I get that the question asks for how to do it without a number, but the title "JavaScript: Get the second digit from a number?" means a lot of people will find this answer when looking for a way to get a specific digit, period.
I'm not bashing the original question asker, I'm sure he/she had their reasons, but from a search practicality standpoint I think it's worth adding an answer here that does convert the number to a string and back because, if nothing else, it's a much more terse and easy to understand way of going about it.
let digit = Number((n).toString().split('').slice(1,1))
// e.g.
let digit = Number((1234).toString().split('').slice(1,1)) // outputs 2
Getting the digit without the string conversion is great, but when you're trying to write clear and concise code that other people and future you can look at really quick and fully understand, I think a quick string conversion one liner is a better way of doing it.
function getNthDigit(val, n){
//Remove all digits larger than nth
var modVal = val % Math.pow(10,n);
//Remove all digits less than nth
return Math.floor(modVal / Math.pow(10,n-1));
}
// tests
[
0,
1,
123,
123456789,
0.1,
0.001
].map(v =>
console.log([
getNthDigit(v, 1),
getNthDigit(v, 2),
getNthDigit(v, 3)
]
)
);
This is how I would do with recursion
function getDigits(n, arr=[]) {
arr.push(n % 10)
if (n < 10) {
return arr.reverse()
}
return getDigits(Math.floor(n/10),arr)
}
const arr = getDigits(myVar)
console.log(arr[2])
I don’t know why you need this logic, but following logic will get you the second number
<script type="text/javascript">
var myVal = 58445456;
var var1 = new Number(myVal.toPrecision(1));
var var2 = new Number(myVal.toPrecision(2));
var rem;
rem = var1 - var2;
var multi = 0.1;
var oldvalue;
while (rem > 10) {
oldvalue = rem;
rem = rem * multi;
rem = rem.toFixed();
}
alert(10-rem);
</script>
function getDigit(number, indexFromRight) {
var maxNumber = 9
for (var i = 0; i < indexFromRight - 2; i++) {
maxNumber = maxNumber * 10 + 9
}
if (number > maxNumber) {
number = number / Math.pow(10, indexFromRight - 1) | 0
return number % 10
} else
return 0
}
Just a simple idea to get back any charter from a number as a string or int:
const myVar = 1234;
String(myVar).charAt(1)
//"2"
parseInt(String(myVar).charAt(1))
//2
you can use this function
index = 0 will give you the first digit from the right (the ones)
index = 1 will give you the second digit from the right (the tens)
and so on
const getDigit = (num, index) => {
if(index === 0) {
return num % 10;
}
let result = undefined;
for(let i = 1; i <= index; i++) {
num -= num % 10;
num /= 10;
result = num % 10;
}
return result;
}
for Example:
getDigit(125, 0) // returns 5
gitDigit(125, 1) // returns 2
gitDigit(125, 2) // returns 1
gitDigit(125, 3) // returns 0
function left(num) {
let newarr = [];
let numstring = num.split('[a-z]').join();
//return numstring;
const regex = /[0-9]/g;
const found = numstring.match(regex);
// return found;
for(i=0; i<found.length; i++){
return found[i];
}
}
//}
console.log(left("TrAdE2W1n95!"))
function getNthDigit(n, number){
return ((number % Math.pow(10,n)) - (number % Math.pow(10,n-1))) / Math.pow(10,n-1);
}
Explanation (Number: 987654321, n: 5):
a = (number % Math.pow(10,n)) - Remove digits above => 54321
b = (number % Math.pow(10,n-1)) - Extract digits below => 4321
a - b => 50000
(a - b) / 10^(5-1) = (a - b) / 10000 => 5
var newVar = myVar;
while (newVar > 100) {
newVar /= 10;
}
if (newVar > 0 && newVar < 10) {
newVar = newVar;
}
else if (newVar >= 10 && newVar < 20) {
newVar -= 10;
}
else if (newVar >= 20 && newVar < 30) {
newVar -= 20;
}
else if (newVar >= 30 && newVar < 40) {
newVar -= 30;
}
else if (newVar >= 40 && newVar < 50) {
newVar -= 40;
}
else if (newVar >= 50 && newVar < 60) {
newVar -= 50;
}
else if (newVar >= 60 && newVar < 70) {
newVar -= 60;
}
else if (newVar >= 70 && newVar < 80) {
newVar -= 70;
}
else if (newVar >= 80 && newVar < 90) {
newVar -= 80;
}
else if (newVar >= 90 && newVar < 100) {
newVar -= 90;
}
else {
newVar = 0;
}
var secondDigit = Math.floor(newVar);
That's how I'd do it :)
And here's a JSFiddle showing it works :) http://jsfiddle.net/Cuytd/
This is also assuming that your original number is always greater than 9... If it's not always greater than 9 then I guess you wouldn't be asking this question ;)