The factorial function does not involve multiplication

Every time I execute the code, it doesn't actually perform the multiplication of my number. Instead, it continues to output in a loop until it reaches 1.

I've attempted various methods and this one is the most promising so far.

    ......................................
    var BR="<br />"; //html line break

    function factorial(Num) {

   document.write("The factorial of your number is" +Num +BR);

   if (Num == 1 ) return 1;

   else return (Num * factorial(Num-1));

    }
.....................................................        





   .......................................
        var Num; //users number
        var Numfactorial;
        var ES="";
               var factorial                     
        Num=prompt("Enter a number between 1-20" +ES);
        Numfactorial=factorial(Num);
     .........................................   

The intended functionality is to take the input number and recursively multiply it down - for example, entering 20 should result in: 20*19*18... continuing until it reaches 1 and then outputs the final product.

Answer №1

Move the document.write statement outside of the function and simply display the result (Numfactorial) on the page. Remember to convert Num into a number by using parseInt, and eliminate the need for var factorial:

var BR = "<br />";
function factorial(Num) {
    if (Num == 1) return 1;
    else return Num * factorial(Num - 1);
}
var Num;
var Numfactorial;
var ES = "";
Num = parseInt(prompt("Please input a number between 1-20" + ES));
Numfactorial = factorial(Num);
document.write("The factorial of the given number is " + Numfactorial + BR);

Answer №2

The code you have written is producing the expected output. However, there is a small modification that can be made to improve it. Instead of just returning the factorial value from your function, you should also display it in the output. Here is how you can do this:

....................................................
var BR="<br />"; //html line break
function factorial(Num) {
   if (Num == 1 ) return 1;
   else return (Num * factorial(Num-1));
}
.....................................................



.......................................
    var Num; //users number
    var Numfactorial;
    var ES="";
           var factorial                     
    Num=prompt("Enter a number between 1-20" +ES);
    Numfactorial=factorial(Num);
    document.write("The factorial of your number is" +Numfactorial +BR);
 .........................................   

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

InvalidTypeError: X cannot be used as a constructor

Currently exploring React and ES6. I have developed a React ES6.js file to practice and understand ES6 features more easily and efficiently. Once the file was created, I imported it into index.js and utilized it in the following manner: // Begin import Re ...

What is the best way to pass a variable using the href tag in jQuery?

for (var i in result) { $('#tgt').append( "<li><a href='/UpdateStatusData/?id='"+result[i]+" >"+result[i]+"</a></li>"); } I am facing an issue where the id is appearing blank when being extracted o ...

Ways to extract value from all chosen dropdown list elements

<table id="tb_Answers"> <tbody> <tr> <td> <select class="ddl_NextQuestion" name="_ctl0"> <option value="0">End</option> <option val ...

Initial part before entering the line of input

Is there a way to add a prefix to input blocks similar to how Python does it? E:\Users\foobar\Downloads\KahootTest1>py Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", ...

How to Send a JSON-formatted object to the Django backend?

When working with JavaScript, I am attempting to convert an Object into JSON and then send it to the back-end in Django. First step involves creating a list of lists: function get_account_info(){ var account_list = []; $('.card').each(f ...

Guide for setting up multiple checkbox event listeners with jQuery

I currently have 2 checkboxes on my form: <form action=""> <input id="bikeCheckbox" type="checkbox" name="bikeCheckbox" value="Bike">I own a bike<br> <input id="carCheckbox" type="checkbox" name="carCheckbox" value="Car">I ...

What steps can I take to ensure my CSS selector for the element is functioning properly?

Here is an example of some code: <html> <head> <style> .test{ background-color: red; p { background-color: yellow; } } </style> </head> <body> <div class="test"> ...

The checkbox selection triggers a JavaScript function, however, it may not capture every value

Encountering an issue with a form that dynamically calculates the cost of an item based on user-selected options. When selecting an option in the first step, it displays the chosen option and moves to the next step where selecting another option will displ ...

Creating a personalized audio player using HTML

I have created a design for an audio player that I would like to implement using the HTML audio player element. https://i.sstatic.net/vJpGg.jpg When I tried <audio></audio>, it just displayed the default player: https://i.sstatic.net/nyNj8.j ...

Ways to iterate and combine two associative arrays in jQuery

I have a total of 15 sections, each known as bases, with their own alphabet buttons. My goal is to link the alphabet letters with their corresponding base/section. For instance, if a user clicks on the letter "B" under base 7, I want to show that the user ...

How can you display content from another page without resorting to scroll bars?

Hey there, I am new to web development and could use some assistance! I have been using jQuery and a snippet of JavaScript code to display content from another page on my site. However, I have noticed that sometimes it causes a scroll bar to appear. For ex ...

Exploring the Depths of Google Chrome: Unleashing the Power of

While a similar question has been posed previously, I am encountering difficulties debugging Javascript in Google Chrome. When I navigate to Page > Developer, the "Debug Javascript" function (Ctrl+Shift+L) is not active. Even trying Alt + ` does not se ...

Which comes first in AngularJS: ng-include or ng-repeat?

What is the outcome if I have a template containing ng-repeat and include it using ng-include? Will the included template have the completed ng-repeat, or will it be included without the ng-repeat being complete (and then completed after inclusion)? ...

Tips on hiding the checkbox within the Material UI TextField input when using MenuItems with checkboxes

I've customized the MenuItems in a TextField of type Select to include checkboxes. However, when I select an item from the menu, the checkbox is also displayed in the input field of the TextField. Requirement: I want to hide the checkbox in the TextF ...

Secure Flask API used for serving JSON files to a basic HTML, JavaScript, and CSS web application

I have developed a basic web application that will display data in a table and be updated on a weekly basis. To perform this update, I utilize Python code in the backend to scrape and modify data before storing it in a SQLite database. After some researc ...

How can you integrate jquery ajax in WordPress?

Recently, I started learning about jquery and have been following a tutorial on creating instant search using jquery. The tutorial can be found here. Now, I am trying to implement this on my WordPress site, but it seems like things work differently when d ...

Is there a way to utilize the 'interval' Rxjs function without triggering the Change Detection routine?

My goal is to display the live server time in my application. To achieve this, I created a component that utilizes the RXJS 'interval' function to update the time every second. However, this approach triggers the Change Detection routine every se ...

JavaScript code to sort an array of objects

Hey everyone, I'm still having trouble sorting out this array properly. The array we need to sort is as follows: const arr = [ {id: 3123124, parentId: 0o0000, title: 'title', type: 'block'}, {id: 3542132, parentId: 312312 ...

Error: JSON parsing failed due to an unexpected character, resulting in null data

Many people have asked similar questions on the same topic, but I have not been able to find a solution for my specific problem. Below is the code snippet that I am working with: $.post("show_search_results.php", {location_name: ""+location_name+"", key: ...

Tips for displaying the overlay in a jQuery UI modal dialog

The demonstration shows that the overlay is displayed correctly and all elements below it are disabled: <div class="ui-widget-overlay" style="width: 1920px; height: 650px; z-index: 1001;"></div> However, on my webpage, I am still able to inte ...