Js function top calculate factorial not working - javascript

I was doing this challenge from coderbyte where you have to make a function that calculate the factorial of a given number, this is my not so working solution.
function firstFactorial(num) {
for (var i = num; i == 1; i--) {
num = num * i;
}
return num;
}
It just returns whatever number i pass in as an argument, and i'm trying to understand what's wrong. Is it something to do with the loop or is it something with the variable scope ?

i == 1 is wired in loop condition it will always be false for all number except 1.So it will always return the same number as result.
i = num should be i = num-1 to get correct factorial.
function FirstFactorial(num) {
for(var i = num-1; i >= 1; i--){
num = num * i;
}
return num;
}
console.log( FirstFactorial(5))

Your for loop was a bit messed up. Now it should work.
function factorial(num){
for(var i = num - 1; i > 0; i--){
num *= i;
}
return num;
}
console.log(factorial(5));

Your problem is that you have a loop condition i == 1. For factorials, it should be i >= 1, or i > 1 depending on what algorithm you use. My take on a factorial function would be:
function calculate(factorial) {
var newFactorial = factorial;
while (factorial > 1) {
factorial--;
newFactorial *= factorial;
}
return newFactorial;
}

function firstFactorial(num) {
const output = eval(Array.from({length: num}, (_, index) => (index + 1)).reverse().join("*"));
return output;
}
console.log(firstFactorial(8));
Rather than iterating through all the numbers using for loop or recursion. I used built-in Javascript functions.
I first created an array of length 1-N using Array.from
Then, I reversed that array and joined it with *. Then, I used the eval function to get evaluate the expression.
You can also shrink it down to just one line. So the code will be:
const findFactorial = num => eval(Array.from({length: num}, (_, index) => (index + 1)).reverse().join("*")

Related

Is it possible to find prime number without using for loops? Can it be done with just the filter method?

In a given array of input x can you find all the prime numbers smaller than x? This can be done with a for loop and I provided my code below. However, I'm really interested in knowing if this can be done without a for loop. Was thinking of a possible way using the filter method?
My for loop code
function findThePrimes(num) {
let nonPrimes = [], i, j, primes = [];
for (i = 2; i <= num; ++i) {
if (!nonPrimes [i]) {
primes.push(i);
for (j = i << 1; j <= num; j += i) {
nonPrimes[j] = true;
}
}
}
return primes;
}
console.log(findThePrimes(100))
Looking for something similar to the code below
function findThePrimes(num) {
numArr = Array.from({length: num}, (v, k) => k+1)
const primeNum = []
const takeOutPrimes = numArr.filter(num => ...not sure what to do next that will push prime numbers into the primeNum array)
}
console.log(findThePrimes(ANY_NUMBER))
#TylerRoper gave me a link to a code that was close but the only thing that was missing was 2 in the prime array. So I set a conditional to allow for 2.
Can this be cleaner????
const isPrime = n => Array(Math.ceil(Math.sqrt(n)+1)).fill().map((e,i)=>i).slice(2).every(m => n%m);
const primeArr = Array(n).fill().map((e,i)=>i+1).slice(1).filter(isPrime)
if (n >= 2) {
primeArr.unshift(2)
}
return primeArr
}
console.log(findPrime(1000).length);```

How to get string from odd's array ?

I need help... I'm learning JavaScript, and it seems easy, but I may just be overlooking... everything... My problem is I need to return a string of all the even numbers between 0 and num inclusive; ex 7 gets you 0246, etc. I've gotten:
function stringOfEvens(num) {
for (let i = 0; i <= num.length; ++i) {
if (i % 2 === 0 ); {
return i;
}
}
}
I know the whole outlook is to run a for loop that goes from 0 to the number in question appending each time and if that number % 2 = 0, return that number, but something is a miss... I may even be overthinking and approaching this whole thing wrong... It is figuratively driving me mad...
function theJob(limit) {
var res = ''; //initialize as a string so that the other numbers will be appended instead of added
for (i = 0; i <= limit; i += 2) { // step increase by 2 to skip odd numbers
res += i;
}
return res; // returning the resulting string
}
console.log(theJob(10));
You can do this without using the modular function, by simply starting the loop at zero and incrementing by 2 each time the loop iterates...
function stringOfEvens(num) {
var result = "";
for (let i = 0; i <= num; i += 2) {
result += i; // append this even number to the result string
}
return result;
}
console.log(stringOfEvens(10));
You're returning the first number you find. a better approach would be to build the string in the loop then return after that string after the loop. Also no need for num.length if num is an int.
function stringOfEvens(num) {
var stringToReturn = "";
for (let i = 0; i <= num; i++) {
if (i % 2 === 0) {
stringToReturn = stringToReturn + i;
}
}
return stringToReturn;
}
function stringOfEvens(num) {
var str= ' ';
for(var i = 0; i <= num; i = i + 2){
str += i;
}
return str;
}
console.log(stringOfEvens(10))
Just for fun, since it's not particularly efficient:
const stringOfEvens = n => Array(~~(n/2)+1).fill().map((_, i) => 2*i).join("")
or annotated:
const stringOfEvens = n => // arrow function definition, returning:
Array(~~(n / 2) +1) // a sparse array of the required length
.fill() // made unsparse, so .map works
.map((_, i) => 2 * i) // then containing the even numbers
.join("") // and converted to a string
or alternatively (and more efficiently) using Array.from which can call an explicit map function in place:
const stringOfEvens = n => Array.from(Array(~~(n/2)+1), (_, i) => 2*i).join("")

Factorize function javascript

I am having a little issue writing a function that factorizes numbers. The hard part is done. However I cannot seem to tell the function to return 1 when num is 0.
PS: which other ways would you write the same function in JavaScript?
var arrOfNum = [];
function factorialize(num) {
for(i = 1; i <= num; i++){
// push all numbers to array
arrOfNum.push(i);
}
// multiply each element of array
var result = arrOfNum.reduce(function(a,b){
return a * b;
});
console.log(result);
}
You already have a for loop, in which you can calculate the factorial at once, without array and reduce.
function factorial(num) {
var result = 1;
for(i = 2; i <= num; i++) {
result *= i;
}
return result;
}
You can use the following method that uses the recursion:
function factorize(num){
if(num === 0){
return 1 ;
}
else {
return num = num * factorize(num-1);
}
}
Roundup:
Declaration of local variable i is missing
var i;
Declaration of other used variables are over the function distributed. A better way is to declare the variables at top of the function.
Array#reduce needs for this task an initialValue as the second parameter.
The first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.
function factorial(num) {
var i,
arrOfNum = [],
result;
for (i = 1; i <= num; i++) {
// push all numbers to array
arrOfNum.push(i);
}
// multiply each element of array
result = arrOfNum.reduce(function (a, b) {
return a * b;
}, 1);
document.write(num+'! = '+result + '<br>');
}
factorial(0);
factorial(1);
factorial(2);
factorial(5);
factorial(8);
Simply return the value 1
function factorialize(num) {
if (num < 1) return 1; //this line is added
for(i = 1; i <= num; i++){
arrOfNum.push(i);
}
var result = arrOfNum.reduce(function(a,b){
return a * b;
});
console.log(result);
}
If you give reduce an initial value of 1, everything will work fine even without an explicit check:
var result = arrOfNum.reduce(function(a,b){
return a * b;
}, 1);
^^^ // PROVIDE EXPLICIT INITIAL VALUE TO REDUCE
function factorial(n) {
return Array.apply(0, Array(n)).reduce(function(x, y, z) {
return x + x * z; //1+(1*0), 1+(1*1),2+(2*2), 6+(6*3), 24+(24*4), ...
}, 1);
}
DEMO
Here's a fairly streamlined function that returns an array of all factors of 'n'
You only need to look at candidates < sqrt(n)
For those of you who don't know the | 0; bit when getting sqrt(n) is a faster equivalent of Math.floor()
As factn is defined after some sanity checking the function will either return undefined or an array which is easy to check with something like if(factors = factorize(n) { success code } sorta structure
There are improvements that can be made to this but they're complex and were beyond the requirements when I wrote it - specifically I used this to calculate CSS sprite sizes from a large image by using factorize on the x + y dimensions of an image then creating a third array of shared factors (which gives you a list of all the possible square sprite sizes).
function factorize(n) {
n = Number(n);
if(n) {
if(n > 1) {
var sqrtn = Math.sqrt(n) | 0;
var factn = [1, n];
var ipos = 0;
for(i = 2; i <= sqrtn; i++) {
if((n % i) == 0) {
ipos++;
if((n / i) !== i) {
factn.splice(ipos, 0, i, n / i);
} else {
factn.splice(ipos, 0, i);
}
}
}
}
}
return factn;
}
Don't know why there are complicated answers. A very simple answer is:
var i;
function factorialOf(num) {
//Initially set factorial as number
var factorial = num;
//A for loop starting with 1 and running the times equal to num
for (i = 1; i < num; i++) {
//Set factorial to the number itself * i
factorial = factorial * i;
}
//Return factorial
return factorial;
}
console.log(factorialOf(5));

Comparing sums of elements within an array to determine which is the highest

I am trying to create a single function in Javascript that will take each element of an array of numbers (specifically phone numbers in this case) and determine which element has the highest sum. I have reached a point where I am feeling pretty defeated, yet I think I am very close. Can anyone give some guidance? This is what I have so far:
function highest(inputArray) {
var sum = 0;
var currentHighest = 0;
var largest = 0;
I set the variables I am going to use, then created a for loop to iterate over each element in the array.
for (a = 0; a < inputArray.length; a++)
var tempArray = inputArray[a].replace(/\D/g,'');
I create a place holder string to remove any non integers in the element, then create a function that will sum all the digits of the element.
function sumDigits(str) {
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i));
return sum;
}
}
Then create an if statement that tests if the sum of the current element is higher or equal to the highest sum element.
if (sumDigits(tempArray) >= currentHighest) {
currentHighest = sum;
largest = inputArray[a];
return largest;
}
else {
return largest;
}
}
var newArray = ['123-456-7777', '963-481-7945', '111-222-3333'];
console.log(highest(newArray));
Here is the entire code block as a whole:
function highest(inputArray) {
var sum = 0;
var currentHighest = 0;
var largest = 0;
for (a = 0; a < inputArray.length; a++)
var tempArray = inputArray[a].replace(/\D/g,'');
function sumDigits(str) {
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i));
return sum;
}
}
if (sumDigits(tempArray) >= currentHighest) {
currentHighest = sum;
largest = inputArray[a];
return largest;
}
else {
return largest;
}
}
}
var newArray = ['123-456-7777', '963-481-7945', '111-222-3333'];
console.log(highest(newArray));
I get "undefined" as the result when I run the code if that helps. Thank you in advance for your assistance.
If I'm interpreting this question correctly (add each number of a phone number, then print the largest result), you can accomplish it like this:
//Define an array of phone numbers
var numbers = ['123-456-7777', '111-222-3333', '963-481-7945'];
//Map takes an array, does something with each element, then returns that result
var sums = numbers.map(function (m) {
//In this case, we return an object containing the original number, and a score
return {
number: m,
//The score is calculated by adding up each number. The match expression creates an array of all terms (g modifier) matching the expression. \d matches a single digit, so we end up with an array of each digit in the number.
//Reduce applies a function to each item in an array, and adds them up
score: m.match(/\d/g).reduce(function (p, c) {
//This looks like magic, but the + before p and c coerces them to numbers (they're strings right now, since match returns an array of strings)
//Both numbers are then added
return +p + +c;
})
}
}).sort(function (a, b) {
//Now that we have the scores of all numbers, we can sort the array to find the highest score
//To be honest, sort() is mostly trial and error for me to find which values to return 1 and -1 for
if (a.score < b.score) return 1;
if (a.score > b.score) return -1;
return 0;
});
//All together, without comments:
sums = numbers.map(function (m) {
return {
number: m,
score: m.match(/\d/g).reduce(function (p, c) {
return +p + +c;
})
}
}).sort(function (a, b) {
if (a.score < b.score) return 1;
if (a.score > b.score) return -1;
return 0;
});
console.log(sums);
document.write("Number with the highest score: " + sums[0].number);
document.write("<br>");
document.write("It's score is " + sums[0].score);
Which prints the number with the largest sum to the console. The sum of the numbers is also available in the object that is returned in the score property.
In your code, you are not initializing the sum variable here and you are prematurely returning the sum value in this function:
function sumDigits(str) {
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i));
return sum;
}
}
It should be this:
function sumDigits(str) {
var sum = 0;
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i), 10);
}
return sum;
}
We can't really see what else is wrong without seeing all the code together in one block so we can see how different parts call each other and interact.
Here's a more compact solution (assuming you're trying to sum the digits in each phone number):
var phoneNumbers = ["123-456-7890", "982-111-9999"];
var sums = phoneNumbers.map(function(p) {
return p.match(/\d/g).reduce(function(sum, num) {
return sum + parseInt(num, 10);
}, 0);
});
var maxSum = Math.max.apply(Math, sums);
// output results in the snippet window
document.write("sums = " + JSON.stringify(sums) + "<br>");
document.write("maxSum = " + maxSum + "<br>");
Here's how it works:
Run .map() on the phone numbers array with the goal of returning an array of sums.
Within the .map() search for all digits, then run .reduce() on that resulting array to accumulate the sum.
Then, to get the max value in the sums array, use Math.max() which can accept the entire array and do the max work for you.

How can I declare a counter inside of my recursive function? (Additive Persistence: Coderbyte)

While working through some Coderbyte challenges, I was able to solve the following problem recursively, but was hoping to get some feedback on how I can improve it.
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.
My submitted, working recursive solution is below. How can I place "count" into my function without letting it get "reset" every time I recurse?
var count = 0;
function AdditivePersistence(num) {
count = 0;
if (num < 10) {
return count;
}
if (num > 10) {
count++;
AdditivePersistence('' + num.split("").reduce(function(a,b) {
return parseInt(a) + parseInt(b)
}));
}
}
Here's my broken attempt at moving the counter within the function... would appreciate any pointers for my beginner-self. Beyond just fixing the code, I'd love it if there are other great methods for solving this puzzle!
function AdditivePersistence(num) {
var count = 0;
(function recurse(num) {
if (num < 10) {
return count;
}
if (num > 10) {
count++;
recurse('' + num.split("").reduce(function(a,b) {
return parseInt(a) + parseInt(b);
}));
}
})();
return count;
}
Edit: I just tried with a while loop below
function AdditivePersistence(num) {
var count = 0;
while (num >= 10) {
count++
num = num.toString().split('').reduce(function(a,b) {
return parseInt(a) + parseInt(b);
})}
return count;
}
Many thanks in advance!
The idea is simple
AdditivePersistence(n):
if n < 10
return 0
else
return 1 + AdditivePersistence(sum-of-digits(n))
Strictly speaking, there's no need for the recursion here - that's essentially a normal while loop.
I'm going to extend #georg's answer and provide a full implementation
var additivePersistance = (function () {
function sumOfDigits (n) {
var ret = 0;
n.toString().split('').forEach(function (i) {
ret += parseInt(i, 10);
});
return ret;
}
return function additivePersistance (n) {
if (n < 10) {
return 0;
}
return additivePersistance(sumOfDigits(n)) + 1;
}
}());
This implementation hides the sumOfDigits as a helper method using a closure.
additivePersistance(2718); // 2
This closure idea can also serve to create a psudo static variable in the recursive function. Follow this form.
var func = (function () {
var staticCounter = 0;
return function func() {
if (staticCounter++ > 20) {
return 0;
}
return func() + 1;
};
}());
Here the body of the inner func method is using the variable staticCounter accross all calls to the outter func.
var count = 0;
function AdditivePersistence(num)
{
// make the number into a string so that each digit can be taken
var num_string = num.toString();
// this will hold each digit
var numbers = [];
// iterate through each digit as a character
for(var i = 0; i < num_string.length; ++i)
{
// add the character converted to a number into the numbers array
numbers.push(parseInt(num_string[i]));
}
// this will hold the value of all the digits added together
var total = 0;
// iterate through the digits
for(var i = 0; i < numbers.length; ++i)
{
// add each digit to the total
total += numbers[i];
}
// if larger than the total
if(total > 10)
{
// increase the count
++count;
// redo it again
AdditivePersistence(total);
}
else
{
// return the total amount of tries
return (++count);
}
}

Categories