Task
Create a program that takes in a number from the user.
- Print all the factors of this given number
- If there are no factors, this is a prime number – report this to the user
Solution
Enter your number:
Code
| function factors() { | |
| //get user input | |
| let userInput = parseInt( document.getElementById(“number-input”).value); | |
| console.log(“User input = ” + userInput); | |
| //check input is a number (parseInt) | |
| let checkType = typeof userInput; | |
| console.log(“Type = ” + checkType); | |
| //display number | |
| document.getElementById(“display-number”).innerHTML = “You selected: ” + userInput; | |
| // program to find the factors of an integer | |
| console.log(`The factors of ${userInput} is:`); | |
| //declare empty variable | |
| let factors=””; | |
| // looping through 1 to num | |
| for(let i = 1; i <= userInput; i++) { | |
| // check if number is a factor | |
| if(userInput % i == 0) { | |
| console.log(i); | |
| factors = factors + i + ” is a factor of ” + userInput + “<br />”; | |
| document.getElementById(“display-factors”).innerHTML = factors; | |
| } | |
| } | |
| } |


