Factorize function javascript - 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));

Related

Js function top calculate factorial not working

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("*")

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("")

simple math javascript sum all data with same variable

function mathx(n){
var total
for(var i = 0; i<n.length; i++){
var sumlah = n[i] * 2;
}
}
mathx('123')
I will multiply all the data in the variable sumlah. On the code snippet there are 3 numbers that will be multiplied by the number 2 if this code is executed it will produce var sumlah = 1 * 2, var sumlah = 2 * 2 and var sumlah = 3 * 3. The result of a sumlah of 2,4,6. And I want to multiply all the data sumlah. I tried using * = but failed.
I recommend to use map:
function mathx(xs) {
return xs.map((x) => x*2);
}
mathx([1,2,3])
That just do the work. maptakes a function and the result replace every value from the list.
Also, don't use a string '123', use a list: [1,2,3].
How about this:
function mathx(n, multiple) {
var digits = n.split('');
return digits.map(function (x) {
return Number.parseInt(x) * Number.parseInt(multiple);
}).reduce(function (x, y) {
return x * y;
});
}
console.log( mathx('123', 2) )
You can be extra fancy by using map and reduce
function mathx(n) {
return n.split('').map(Number).reduce(function(acc, val) {
return acc + (val * 2);
}, 0);
}
alert(mathx('123'));
JSFiddle: click here
You need to initialize sumlah to 1, then use *= to multiply each result into it. And you have to return the result.
function mathx(n) {
var sumlah = 1;
for (var i = 0; i < n.length; i++) {
sumlah *= n[i] * 2;
}
return sumlah;
}
console.log(mathx('123'));
I believe this will work for what you want:
function mathx(n) {
var sumlah = 1;
for (var i = 0; i < n.length; i++) {
sumlah *= n[i] * 2;
}
return sumlah;
}
alert(mathx('123'));
You had two variables that you I believe were supposed to be the same - total and sumlah.
Your biggest problem is that sumlah was declared inside the for loop. By declaring it outside of the loop, it has scope outside the loop.
You want to calculate twice the current number with n[i] * 2. Then, multiply it into the accumulator sumlah with sumlah *= n[i] * 2;. When you are done, return it with return sumlah;.
However, it is best not to use a string to store numeric data. Try an array instead: [1, 2, 3]. Then you can do this:
function mathx(n) {
var sumlah = 1;
for (var i = 0; i < n.length; i++) {
sumlah *= n[i] * 2;
}
return sumlah;
}
alert(mathx([1, 2, 3]));
Which is almost the same, but makes sense to other people.

How can I get the sum of all odd fibonacci vales in javaScript?

I am working through this Free Code Camp exercise.
Return the sum of all odd Fibonacci numbers up to and including the
passed number if it is a Fibonacci number. The first few numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and
8, and each subsequent number is the sum of the previous two numbers.
And here is what I have so far...
Any suggestions?
function sumFibs(num) {
var arr, isFibVal, isEvenVal, sum, i = 0, fibonacci = function (num){
var a, b, result, fibArr = [1];
a=0;
b=1;
result=b;
for(var j = 0; j < num; j++){
result = a + b;
a = b;
b = result;
fibArr.push(result);
}
return fibArr;
},
isFib = function (val){
var prev = 0;
var curr = 1;
while(prev<=val){
if(prev == val){
return true;
} else {
return false;
}
curr = prev + curr;
prev = curr - prev;
}
},
isEven = function(someNumber){
return (someNumber % 2 === 0) ? true : false;
};
function sumArray(array) {
for (
var
index = 0, // The iterator
length = array.length, // Cache the array length
sum = 0; // The total amount
index < length; // The "for"-loop condition
sum += array[index++] // Add number on each iteration
);
return sum;
}
arr = fibonacci(num);
isFibVal = isFib(num);
isEvenVal = isEven(num);
if (isFibVal && !isEvenVal){
sum += sumArray(arr);
}
return sum;
}
All I get back is undefined which seems to be weird because i thought this part of my code was pretty cool—using the function values to check vs. in the if statement.
arr = fibonacci(num);
isFibVal = isFib(num);
isEvenVal = isEven(num);
if (isFibVal && !isEvenVal){
sum += sumArray(arr);
}
I won't give you the answer outright since you're going through FCC, but I'll provide you with some hints as to where to look:
See this segment:
for(var j = 0; j < num; j++){
result = a + b;
a = b;
b = result;
fibArr.push(result);
}
And this one:
function sumArray(array) {
for (
var
index = 0, // The iterator
length = array.length, // Cache the array length
sum = 0; // The total amount
index < length; // The "for"-loop condition
sum += array[index++] // Add number on each iteration
);
return sum;
}
Also, you probably don't need this segment at all:
isFibVal = isFib(num);
isEvenVal = isEven(num);
if (isFibVal && !isEvenVal){
sum += sumArray(arr);
Good luck. As someone who has finished a good chunk of the curriculum, I can say that Free Code Camp is the real deal.
You're pretty close and the other answer is good for pushing you in the right direction, I'll post a different way that does this using native JS functions:
Example of the code below in JSBin
function fibs(n) {
var f = [0, 1];
var extraNumber = 0;
for (var i = 0; i < n; i++) {
f.push(f[f.length - 1] + f[f.length - 2]);
}
// lets check if the passed in number is a fib:
if (f.indexOf(n) > -1) {
extraNumber = n;
}
console.log(f); // just to check we can cut all the logs later...
var filtered = f.filter(function(num) {
// filter out the even numbers
return num % 2 === 1;
});
console.log(filtered);
var sum = filtered.reduce(function(a, b) {
// add up whats left
return a + b;
});
console.log(sum);
return sum + extraNumber;
}
heres my solution, and i find it to be pretty readable:
function sumOddFibs(num) {
// initialize with 2 because
// fib sequence starts with 1 and 1
var sum = 2;
var prev = 1;
var curr = 1;
var next = 2;
while (next <= num) {
prev = curr;
curr = next;
next = prev + curr;
if (curr % 2 !== 0) {
sum += curr;
}
}
return sum;
}
You could start by defining variables for the previous number, current number, and total Fibonacci
To check for odd numbers, you could use an if statement and use %:
if (currNum % 2 !== 0){ }
If current number is odd, then you add it to the total
fibTotal += currNumber;
To determine the next Fibonacci number you, you will need to add the previous and current number:
var nextNumber = prevNumber + currNumber;
You will need to update the previous number to the current one
prevNumber = currNumber;
Set the current number to the next Fibonacci number in the sequence
currNumber = nextNumber;
Hope this helps.

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