1

this is my second post today as the original wasn’t clear and I was urged to repost because despite getting some good answers they did not fit the requirements of the code. I have been challenged to write a program in JavaScript that allows the user to perform several tasks, one of which is to ask the user for a number and calculate the factorial of that number and then display it in the format listed in the requirements. As I do not know much about Java script I used already asked questions and managed to get the calculation to work but could not figure out how to get the required output whilst still meeting the requirements.

Requirements: • Can only use the provided variables Number (variable initialised as 0 to hold user input) Factorial (variable initialised to 1 to hold value of calculated factorial) Count (variable to hold number of times loop is executed for performing factorial calculation). This is a limitation set by the challenge and not me • Cannot use fancy libraries • Need to use a loop solution for the output. The answers on the other post required introducing new variables, perhaps it is my lack of understanding but perhaps the poorly written pseudo code I have obtained since the last post may help. • Be output in the format: (it is an alert so that part of the program is fine)

The factorial of 5 is 5*4*3*2*1=120 
OR
5! is  5*4*3*2*1=120 

Poorly written pseudo code:

enter image description here

Code:

//prompts the user for a positive number
var number = parseInt(prompt("Please enter a positive number"));
console.log(number);
//checks the number to see if it is a string
if (isNaN(number))
{
  alert("Invalid. Please Enter valid NUMBER")
}

//checks the number to see if it is negaive
else if (number < 0) 
{
  alert("Please Enter valid positive number");
}

//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
    let factorial = 1;
    for (count = 1; count <= number; count++) {
        factorial *= count;
         }
    
    //Sends the inital number back to the user and tells them the factorial of that number
    alert("The factorial of " + number + " is " + factorial + ".");
}




I know there are many similar questions, including my first post which this one now succeeds as I looked around and used them to help me get this far but it is getting the output into the required format that I'm struggling with. I am told it is possible with a loop but do not know where to begin implementing that and I'm only allowed to use that solution.

Again, I would like to apologise for my first post, the given answers would work great if not for the incredibly ridiculous restrictions set by the challenge provider, who is also responsible for giving me rubbish pseudo code, which isn't what I'm going for but I am using to consider the loop.

I appreciate the time it takes to read this amd provide solutions so I will go back and try and mark all working answers in the last post for any normal problems people might search for answers for.

  • you already have a loop to calculate factorial. Define a variable "factorialString" before this loop, then in the loop just concatenate : factorialString = '*' + count + factorialString; This will generate a string "*5*4*3*2*1" When you're out of the loop, just trim the leading star, and there you go... from there it's just about printing this string in the sentence you need... – Laurent S. Nov 19 '20 at 20:46
  • @LaurentS.Thank you for the suggestion. I am getting the feeling that it is impossible to do without introducing new variables as so far all solutions have introduced new arrays and variables in some form. It is frustrating as these are all good functional ideas but the challenge does not permit which is causing the growing suspicion that the challenge is designed to be frustratingly impossible. Thank you regardless. –  Nov 19 '20 at 20:50
  • Sorry I missed that :-/ are there any other requirement? Are you free to choose how you output (for example through console...)? I'm sure if you post it in codegolfSE you'll be getting 5 bytes answers though :-) – Laurent S. Nov 19 '20 at 21:01
  • @LaurentS. Damn you're right so sorry I thought I got them all that time. This is only a small part of a larger program that uses alerts with menus so I beleive it has to be alerts and the console log was for debugging and to confirm the user input number. –  Nov 19 '20 at 21:03

1 Answers1

1

This is a bit of a dirty hack but it should satisfy the condition that no other variables than number, count, and factorial are used.

let number = 5;
let factorial = 120; 
// ^ Do your own calculation for this

alert(`The factorial of ${number} is ${Array.from(Array(number + 1).keys()).slice(1).reverse().join("*")}=${factorial}`)

So what is going on here? We use an interpolated template string to produce the desired output, expressions inside ${these things} are evaluated as strings. And what is the mess we put in there?

Array.from(Array(number + 1).keys())

The expression above creates the array [0,1,2,3,4,5].

.slice(1) gives us [1,2,3,4,5]

.reverse() gives us [5,4,3,2,1]

join("*") gives us "5*4*3*2*1"

Which when all put together gives us The factorial of 5 is 5*4*3*2*1=120

And voila! The output is printed in the desired format without introducing any new variables.

Edit: Oh and you do not need to use an interpolated string for this. You may as well concatenate regular strings together as you have done in your question. e.g.

 "The factorial of " + factorial + " is " + Array.from(Array(number + 1).keys()).slice(1).reverse().join("*") + "=" + factorial
Jim Nilsson
  • 838
  • 4
  • 12
  • Very interesting! So I could change number to be an input without really hindering the program but what about factorial? I think I misread do you mean substitute the top lines with my code and then slot in your output? I will give that a go. –  Nov 19 '20 at 21:28
  • Wow yes just tested just now it works! Thank you so much that should satisfy the challenge! Now I just need to integrate that into a larger program but that's my problem :) –  Nov 19 '20 at 21:31
  • 1
    The top two lines in my example was just for the code snippet to run. The way I understood it was that you just had a problem with writing the output without introducing new variables. So yes, my answer only shows how to print the `n*(n-1)*(n-2)...*1=n!` part. Glad it helped! But I do believe whoever gave you this challenge did not consider the difficulty in producing the desired output without introducing another variable. – Jim Nilsson Nov 19 '20 at 21:31