Factorialize a Number - javascript

I'm taking the freecodecamp course one of the exercises it's to create a Factorialize function, I know there is several ways to do it just not sure what this one keeps returning 5
function factorialize(num) {
var myMax = num;
var myCounter = 1;
var myTotal = 0;
for (i = 0; i>= myMax; i++) {
num = myCounter * (myCounter + 1);
myCounter++;
}
return num;
}
factorialize(5);

This is a recursive solution of your problem:
function factorialize(num) {
if(num <= 1) {
return num
} else {
return num * factorialize(num-1)
}
}
factorialize(5)
This is the iterative solution:
function factorialize(num) {
var cnt = 1;
for (var i = 1; i <= num ; i++) {
cnt *= i;
}
return cnt;
}
factorialize(5)
with argument 5, it will return the 5! or 120.

To answer your question, why your function is returning 5:
Your function never reaches the inner part of the for-loop because your testing if i is greater than myMax instead of less than.
So you are just returning your input parameter which is five.
But the loop does not calculate the factorial of num, it only multiplies (num+1) with (num+2);

My solution in compliance with convention for empty product
function factorializer(int) {
if (int <= 1) {
return 1;
} else {
return int * factorializer(int - 1);
}
}

Here is another way to solve this challenge and I know it is neither the shortest nor the easiest but it is still a valid way.
function factorialiaze(num){
var myArr = []; //declaring an array.
if(num === 0 || num === 1){
return 1;
}
if (num < 0){ //for negative numbers.
return "N/A";
}
for (var i = 1; i <= num; i++){ // creating an array.
myArr.push(i);
}
// Reducing myArr to a single value via .reduce:
num = myArr.reduce(function(a,b){
return a * b;
});
return num;
}
factorialiaze(5);

Maybe you consider another approach.
This solution features a very short - cut to show what is possible to get with an recursive style and a implicit type conversion:
function f(n) { return +!~-n || n * f(n - 1); }
+ convert to number
! not
~ not bitwise
- negative
function f(n) { return +!~-n || n * f(n - 1); }
var i;
for (i = 1; i < 20; i++) {
console.log(f(i));
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

Try this function
const factorialize = (num) => num === 0 ? 1 : num * factorialize(num-1)
Use it like this:
factorialize(5) // returns 120

Try this :
function factorialize(num) {
var value = 1;
if(num === 1 || num ===0) {
return value;
} else {
for(var i = 1; i<num; i++) {
value *= i;
}
return num * value;
}
}
factorialize(5);

// My solution
const factorialize = num => {
let newNum = 1;
for (let i = 1; i <= num; i++) {
newNum *= i
}
return newNum;
}

I love syntactic sugar, so
let factorialize = num => num <= 1 ? num : num * factorialize(num -1)
factorialize(5)

Related

Creating an Iterative - Javascipt

I have a recursive function below and I was just wondering how can I create an iterative (i.e. loops without recursion) for the same thing. I would really appreciate any help or suggestions thank you!
function countPalindromes(string, count) {
if (string.length <= 1) {
return count;
}
let [ firstLetter ] = string;
let lastLetter = string[string.length - 1];
if (firstLetter === lastLetter) {
let stringWithoutFirstAndLastLetters = string.substring(1, string.length - 1);
return countPalindromes(stringWithoutFirstAndLastLetters, count + 1);
} else {
return count;
}
}
console.log(countPalindromes("level", 0));
console.log(countPalindromes("aya", 0));
Took me a while, but this should work.
function countPalindromes(string, count) {
for (i = 0; i < Math.floor(string.length/2); i++) {
if (string.charAt(i) === string.charAt(string.length - i-1)) {count++};
}
return count;
}
console.log(countPalindromes("level", 0));
console.log(countPalindromes("aya", 0));
You can do something like this:
function countPalindromes(string) {
let count = 0;
for (let i = 0; i < Math.floor(string.length / 2); i++) {
const letterFromTheStart = string[i];
const letterFromTheEnd = string[(string.length - 1) - i];
if (letterFromTheStart !== letterFromTheEnd) {
break;
}
count++;
}
return count;
}
console.log(countPalindromes("level"));
console.log(countPalindromes("aya"));
The important parts are i < Math.floor(string.length / 2) and (string.length - 1) - i.
The first one assures the loop stops before or at the half of the string and the second gets the nth character starting from the string's end.
I didn't get your recursive palindrome function. Just converted the recursive one to iterative one.
function countPalindromes(string, count) {
if (string.length <= 1) {
return count;
}
let i = 0, j = string.length-1;
for (; i < j && string[i] == string[j]; i++, j--);
return i;
}
console.log(countPalindromes("level", 0));
console.log(countPalindromes("aya", 0));
You can reverse the string and compare letters until you hit a mismatch returning the last index that matched plus one.
function isPalindrome(word) {
const drow = word.split('').reverse();
for (i = 0; i < drow.length && drow[i] === word[i]; i++);
return i;
}
console.log(isPalindrome("level"));

Sum All Primes Below a Given Number | Intermediate Javascript Algorithm | Recursion

Question
A prime number is a whole number greater than 1 with exactly two divisors: 1 and itself. For example, 2 is a prime number because it is only divisible by 1 and 2. In contrast, 4 is not prime since it is divisible by 1, 2 and 4.
Rewrite sumPrimes so it returns the sum of all prime numbers that are less than or equal to num.
My Attempt
const isPrime = a => {
for(let i = 2; i < a; i++)
if(num % i === 0) return false;
return a > 1;
}
function sumPrimes(num, total = []) {
let numVar = num;
let n = total.reduce((aggregate, item)=>{
return aggregate + item;
}, 0);
if(n > numVar){
return n;
}
for(let i = 1; i <= numVar; i++){
if(isPrime(i)== true){
total.push(i);
}
}
return sumPrimes(num, total);
}
sumPrimes(10);
The Problem
It says: 'Num is not defined'
I am not sure if there are other errors.
My Question
Please could you help me find the error, and fix the code to solve the algorithm?
This was a simple syntax error identified by #Jonas Wilms (upvote him in the comment above :))!
By replacing the 'a' with 'num' the function was fixed.
const isPrime = a => {
for(let i = 2; i < a; i++)
if(a % i === 0) return false;
return a > 1;
}
function sumPrimes(num, total = []) {
let numVar = num;
let n = total.reduce((aggregate, item)=>{
return aggregate + item;
}, 0);
if(n > numVar){
return n;
}
for(let i = 1; i <= numVar; i++){
if(isPrime(i)== true){
total.push(i);
}
}
return sumPrimes(num, total);
}
console.log(sumPrimes(10));
this simple function may help you,
function isPrime(num) {
for (var i = 2; i < num; i++)
if (num % i === 0) return false;
return num > 1;
}
function sumPrimes(num) {
let tot = 0;
for (let i = 0; i < num; i++)
if (isPrime(i))
tot += i;
return tot;
}
console.log(sumPrimes(10));

Check Digit Sum Javascript- recursion [duplicate]

This question already has answers here:
Adding digits from a number, using recursivity - javascript
(6 answers)
Closed 8 months ago.
Looking for Javascript solution in recursion to get the sum of all digits in number until single digit come as result
For example, for the number is "55555" the sum of all digits is 25. Because this is not a single-digit number, 2 and 5 would be added, and the result, 7.
I tried the below solution based on the algorithm.
function getSum(n) {
let sum = 0;
while(n > 0 || sum > 9)
{
if(n == 0)
{
n = sum;
sum = 0;
}
sum += n % 10;
n /= 10;
}
return sum;
}
console.log(getSum("55555"));
This would kind of work, but I'm almost sure there's a beautiful one-line solution which I just don't see yet.
function singleDigitSum(str) {
str = [...str].reduce((acc, c) => { return Number(c) + acc }, 0)
while (str.toString().length > 1) {
str = singleDigitSum(str.toString());
}
return str
}
console.log(singleDigitSum("55555"))
Explanation:
As a first step in your function you reassign to the parameter passed to the function the result of a reducer function which sums up all numbers in your String. To be able to use Array.prototype.reduce() function, I'm spreading your str into an array using [...str].
Then, for as often as that reducer returns a value with more than one digit, rinse and repeat. When the while loop exits, the result is single digit and can be returned.
function checSumOfDigit(num, sum = "0") {
if (num.length == 1 && sum.length !== 1) {
return checSumOfDigit(Number(sum) + Number(num) + "", "0");
} else if (num.length == 1) {
return Number(sum) + Number(num);
}
num = num.split("")
sum = Number(sum) + Number(num.pop());
return checSumOfDigit(num.join(""), sum + "")
}
console.log(checSumOfDigit("567"));
console.log(checSumOfDigit("123"));
console.log(checSumOfDigit("55555"));
this code might be help you
If you need a recursion try this one
function CheckDigitSum(number) {
let nums = number.split('');
if (nums.length > 1) {
let sum = 0;
for (let i = 0; i < nums.length; i++) {
sum += Number(nums[i]);
}
return CheckDigitSum(sum.toString());
} else {
return parseInt(nums[0], 10);
}
}
Here you go:
function createCheckDigit(num) {
var output = Array.from(num.toString());
var sum = 0;
if (Array.isArray(output) && output.length) {
for ( i=0; i < output.length; i++){
sum = sum + parseInt(output[i]);
}
if ((sum/10) >= 1){
sum = createCheckDigit(sum);
}
}
return sum;
}
This can be calculated by recursive function.
function createCheckDigit(membershipId) {
// Write the code that goes here.
if(membershipId.length > 1){
var dgts = membershipId.split('');
var sum = 0;
dgts.forEach((dgt)=>{
sum += Number(dgt);
});
//console.log('Loop 1');
return createCheckDigit(sum + '');
}
else{
//console.log('Out of Loop 1');
return Number(membershipId);
}
}
console.log(createCheckDigit("5555555555"));
function checkid(num) {
let sum = 0;
let s = String(num);
for (i = 0; i < s.length; i++) {
sum = sum + Number(s[i]);
}
if(String(sum).length >= 2) return checkid(sum)
else return sum;
}
console.log(checkid(55555);

JavaScript Function Arrays

How would I use a function that returns the sum of a given array while getting the sum of the even numbers and sum the odd numbers? I'm not understanding how that is done. Can someone please explain a little more in depth?
Here is my entire code:
function main()
{
var evenNum = 0;
//need a total Even count
var oddNum = 0;
//need a total Odd count
var counter = 1;
var num = 0;
function isOdd(x) {
if ((num % 2) == 0)
{
return false;
}
else
{
return true;
}
}
function isEven(x) {
if ((num % 2) == 0)
{
return false;
}
else
{
return true;
}
}
for (counter = 1; counter <= 100; counter++)
{
num = Math.floor(1 + Math.random() * (100-1));
var total = 0;
for(var j = 0; j < length; j++)
total += a[j];//Array?
console.log(num);
console.log("The count of even number is " + evenNum);
console.log("The count of odd number is " + oddNum);
return 0;
}
main()
If I understand your question correctly, you need a function that returns two values, one for the sum of even numbers and one for the sum of odd numbers. It's not clear if you use even/odd referring to the index of the array or the values in array.
In both cases you can return an object that contains both values:
function sum(array) {
var evenSum = 0;
var oddSum = 0;
...calculate...
var res = {};
res.evenSum = evenSum;
res.oddSum = oddSum;
return res;
}
Hope this will help

sorting an alphanum array using jQuery

i am trying to compare two arrays containing alphabets and numbers using jquery but a call to the function does nothing.
jQuery.compare = function (string2,string1) {
alert("comparing")
var i, j;
for ( i = 0, j=0; i < string2.length|| j<string1.length; ++i,++j) {
var n1 = 0,n2=0;
if ($.isNumeric(string2[i+1])) {
num=string2[i]
while ($.isNumeric(string2[i+1])) {
i++;
num += string2[i]
}
n1 = 1;
}
if ($.isNumeric(strin1[j])) {
num1 = string1[j]
while ($.isNumeric(string1[j+1])) {
j++;
num1 += string1[j]
}
n2 = 1;
}
if (n1 == 1) {
if (n2 = 1) {
if( parseInt(num1) - parseInt(num) !=0)
return parseInt(num1) - parseInt(num);
}
else
return 1;
}
else if (n2 = 1)
return -1;
else {
if(string2[i]-string1[j]!=0)
return string2[i]-string1[j]!=0;
}
}
if (j < string1.length)
return -1;
else
return 1;
}
Also i would like to know the best way to call this function. I would like to use something like string1.compare(string2) and replace string1 with 'this' in the above code fragment.
EDIT:
This is how i call the compare function.Here, colValues is an array of string.
$.fn.sort = function (colValues) {
alert("sorting")
var i;
for (i = 0; i < colValues.length; ++i) {
for (var j = 0; j < i - 1; ++j) {
alert("before compare")
if(colValues.compare(colValues[j],colValues[j + 1])) {
var temp = colValues[j];
colValues[j] = colValues[j + 1];
colValues[j + 1] = temp;
}
}
}
return colValues
}
if i replace
if(colValues.compare(colValues[j],colValues[j + 1]))
with
if(colValues[j]>colValues[j+1])
my sort function works.
i am a complete newbie at coding in jquery. There is probably some syntactical error. I dont really want any help with the algorithm just the syntax.
jsfiddle-checkout my code here
EDIT2:
i fixed everything thx to metadings.
heres what i had to change
1)
jQuery.compare
to
$.fn.compare
2)
if($.isNumeric(string2[i+1]))
to
if(jQuery.isNumeric(string2[i + 1]))
somehow the
while ($.isNumeric(string1[j+1]))
syntax worked without any changes
3)
parseInt(num1) - parseInt(num)
didnt work either as it returned NaN. To solve this problem i defined two var variables 'number1' and 'number2' and initialized them with 0's and assigned parseInt(num1) individually to the variables and then subtracted the new variables.

Categories

Resources