find the trailing zeroes of the factorial [duplicate] - javascript

This question already has answers here:
factorial with trailing zeros, but without calculating factorial
(4 answers)
Closed 3 months ago.
the question asks that how many zeros are their at the end of the digit,
for example if factorial of 5 is 120 then result is 1 because there is only one zero at the end if there was 2 zeros then result is 2.
so I have traied this logic in javascript to solove this problem, and for different numbers its working but for some test cases its not showing the desired output.
Can't figure out why am getting the error, if any one has a better optimized code please do share and point out the mistake that am doing
const fun=(n)=>
{
let fact = 1;
let counter = 0;
for (let i = 1; i <= n; i++) {
fact *= i
}
while (fact % 10 == 0) {
let val = fact / 10;
fact = val;
counter++
}
return counter
}
console.log(fun(5))

Your function works for all numbers as long as they don't become too big, javascript has a hard time with big numbers. One easy way to fix it is to count the zeros while doing the factors.
const fun=(n)=>
{
let fact = 1;
let counter = 0;
for (let i = 1; i <= n; i++) {
fact *= i;
if(fact % 10 == 0){
fact/=10;
counter++;
}
}
return counter
}
console.log(fun(24));
This still has a limit, but might be high enough.

Related

get always 10 numbers from randoms - Javascript [duplicate]

This question already has answers here:
Want to produce random numbers between 1-45 without repetition
(4 answers)
Closed 4 years ago.
I need help with my code. I want to get 10 random numbers every time it rolls and it can't have duplicated, this is my code:
for(let j = 1; j <= 21; j++) {
const number = (Math.floor((Math.random() * j) + 1))
const genNumber = array.indexOf(number);
if (genNumber === -1) {
array.push(number);
}
}
I have no idea how I can get exactly 10 numbers every time, anyway it can be written with js or jquery it doesnt metter for me. Hope I can get help here.
I don't really understand what your code is intended to do, but to get exactly 10 unique random numbers I'd use a Set and loop until it's filled. I have no idea why you loop 21 times for 10 items though...
let s = new Set();
while (s.size < 10) {
s.add((Math.floor(Math.random() * 21 /* ??? */) + 1));
}
console.log([...s]);
You're almost there, but instead of using a for loop, use a while loop that continues as long as there are less than 10 things in the array:
const array = [];
const j = 21; // Pick numbers between 1 and 21 (inclusive)
while (array.length < 10) {
const number = (Math.floor((Math.random() * j) + 1))
const genNumber = array.indexOf(number);
if (genNumber === -1) {
array.push(number);
}
}
console.log(array);

javascript program without using math. pow, find power of any number using for loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I need to know the code built in for the syntax math.pow(x,y). Actually I used the syntax to find exponent of any number... e.g.
var e = Math.pow(-3, 3); yields -27 but couldn't find out the program behind this... Help me please
If you know what power means..
multiplying the number x n times where x is base and n is exponent.
So you just have to repeat the same thing over and over - and that's why loops are for:
var sum = 1; //note that it's not zero!
for (int i=0;i<n;i++) { //loops n times
sum = sum * x; //on each loop multiplies sum by base number
}
Did you mean alternative for Math.pow? Here is one way with simple loop.
function pow(base,power) {
var p = 1;
for (var i=0; i<power; i++) {
p *= base;
}
return p;
}
You can also use recursion to solve this kind of challenge. Beware that recursion has the disadvantage of increasing space complexity as compared to a for-loop.
function pow(base, power) {
if (power === 1) return base * power
return base * pow(base, power - 1)
}
This is a better way to calculate power of a number with recursion:
function power(base, exp) {
if(exp === 0){
return 1;
}
return base * power(base, exp - 1);
}
You can try this:
function pow(n, e) {
let num = n;
for (let i = 1; i < e; i++) {
num *= n;
}
return num;
}
console.log(pow(-3, 3));
It will give you the required result.

Codefights: Correct solution but system does not accept it

Experienced codefighters, i have just started using Codefight website to learn Javascript. I have solved their task but system does not accept it. The task is to sum all integers (inidividual digit) in a number. For example sumDigit(111) = 3. What is wrong with my code? Please help me.
Code
function digitSum(n) {
var emptyArray = [];
var total = 0;
var number = n.toString();
var res = number.split("");
for (var i=0; i<res.length; i++) {
var numberInd = Number(res[i]);
emptyArray.push(numberInd);
}
var finalSum = emptyArray.reduce(add,total);
function add(a,b) {
return a + b;
}
console.log(finalSum);
//console.log(emptyArray);
//console.log(res);
}
Here's a faster trick for summing the individual digits of a number using only arithmetic:
var digitSum = function(n) {
var sum = 0;
while (n > 0) {
sum += n % 10;
n = Math.floor(n / 10);
}
return sum;
};
n % 10 is the remainder when you divide n by 10. Effectively, this retrieves the ones-digit of a number. Math.floor(n / 10) is the integer division of n by 10. You can think of it as chopping off the ones-digit of a number. That means that this code adds the ones digit to sum, chops off the ones digit (moving the tens digit down to where the ones-digit was) and repeats this process until the number is equal to zero (i.e. there are no digits left).
The reason why this is more efficient than your method is that it doesn't require converting the integer to a string, which is a potentially costly operation. Since CodeFights is mainly a test of algorithmic ability, they are most likely looking for the more algorithmic answer, which is the one I explained above.

Massive for loop taking too long to load

I'm working on a program designed to generate prime numbers, and I'm trying to find the 10001st prime number. Each time the loop runs, it tests variable i to see if it's divisible by variable j, which is part of another loop that goes up to half of i. If i is divisible by j then it adds one to variable prime, and when the loop's done it checks to see if variable prime is larger than two; if it is, then i is not prime. If it is prime, it gets push()ed to the variable array, which stores all the primes. Sorry if that's a little confusing.
My problem is that although this code works, whenever I set the first for loop too high (here I have it end at 100000), my browser freezes:
var prime = 0;
var array = [];
for(var i = 2; i <= 100000; i+=1) {
var prime = 0;
for(var j = 0; j <= i/2; j+=1) {
if(i % j === 0) {
prime += 1;
}
}
if(prime < 2) {
array.push(i);
}
}
console.log(array.length)
I know I could just copy and paste all the prime numbers but I want to make the program work. Any ideas to make the program stop freezing?
This is because the time complexity of your algorithm is pretty much O(n^2). Sieve of Eratosthenes created a better algorithm that will prevent your browser from freezing.
Here is one way of doing it:
var exceptions = {
2: 2,
3: 3,
5: 5,
7: 7
}
var primeSieve = function (start, end) {
var result = [];
for (start; start < end; start++) {
if (start in exceptions) result.push(start);
if (start > 1 && start % 2 !== 0 && start % 3 !== 0 && start % 5 !== 0 && start % 7 !== 0) {
result.push(start);
}
}
return result;
};
You can obviously make this look prettier, but I just did it quickly so you can get the point. I hope this helps! Let me know if you have further questions.

Using Recursion for Additive Persistence

I'm trying to solve a Coderbyte challenge, and I'm still trying to fully understand recursion.
Here's the problem: Using the JavaScript language, have the function AdditivePersistence(num) take the num parameter being passed which will always be a positive integer and return its additive persistence which is the number of times you must add the digits in num until you reach a single digit. For example: if num is 2718 then your program should return 2 because 2 + 7 + 1 + 8 = 18 and 1 + 8 = 9 and you stop at 9.
Here's the solution I put into jsfiddle.net to try out:
function AdditivePersistence(num) {
var count=0;
var sum=0;
var x = num.toString().split('');
for(var i=0; i<x.length; i++) {
sum += parseInt(x[i]);
}
if(sum.length == 1) {
return sum;
}
else {
return AdditivePersistence(sum);
}
}
alert(AdditivePersistence(19));
It tells me that there's too much recursion. Is there another "else" I could put that would basically just re-run the function until the sum was one digit?
One of the problems is that your if statement will never evaluate as 'true'. The reason being is that the sum variable is holding a number, and numbers don't have a length function. Also, as 'Barmar' pointed out, you haven't incremented the count variable, and neither are you returning the count variable.
Here's a solution that works using recursion.
function AdditivePersistence(num) {
var result = recursive(String(num).split('').reduce(function(x,y){return parseInt(x) + parseInt(y)}), 1);
function recursive(n, count){
c = count;
if(n < 10)return c;
else{
count += 1
return recursive(String(n).split('').reduce(function(x,y){return parseInt(x) + parseInt(y)}), count)
}
}
return num < 10 ? 0 : result
}
To fix the 'too much recursion problem',
if(sum.toString().length == 1)
However, as the others have said, your implementation does not return the Additive Persistence. Use James Farrell's answer to solve the Coderbyte challenge.

Categories