trishnegs
trishnegs

Reputation: 9

What function(s) would I use to complete my program? For-loop and what else?

I need help finishing this simple program.

The program should ask the user for base number and number of factors, and, upon clicking a button, the program should display the factors that have no remainder.

Here's an example:

    First Factors Game
        Base Number: ___ (user enters 100)
  Number of Factors: ___ (user enters 3)
     [Display Factors!]  (user clicks button)

         Results:
  The first 3 factors of 100 
       are 1, 2, and 4.

In the above program, 1 is displayed, 2 is displayed, the number 3 is NOT displayed because (100%3 !== 0), and 4 is displayed. It stops there because the user only entered 3 in Number of Factors.

So! Here's my HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Audition</title>
    </head>
    <body>
        <h3>First Factors</h3>
        <div id="container">
            <label>Base Number: </label>
                <input id="baseNumber" type="text">
                <br>
            <label>Number of Factors: </label>
                <input id="numberOfFactors" type="text">
                <br>
            <button onClick="displayFactors">Display Factors</button>
        </div>
        <div id="results">
            <p>The first <span id="numberOfFactorsResults"></span> factors 
            of <span id="baseNumberResults"></span> are </p>
        </div>
    </body>
</html>

And here's my JavaScript:

function displayFactors() {
    run();
}

function run(){
    var x = parseInt(document.getElementById("baseNumber").value);
    var y = parseInt(document.getElementById("numberOfFactors").value);
    document.getElementById("baseNumberResults") = x;
    document.getElementById("numberOfFactorsResults") = y;

    /** So, we want to take the base number (entered by the user), divide   
        that base number by numbers leading up to the base number, 
        but only print the first such-and-such factors (number provided by 
        the user) with a remainder of 0. **/

This is where I am stumped. I'm pretty sure I will need to use a for-loop with maybe some nested switch statements, and I know the modulus will come into play at some point, but I don't know where to start. What loops would I use at this point? (Could you also explain why?)

I am not asking you to finish the program for me (although you're welcome to). All I'm asking for is guidance (note: steps would be great!) figuring out how to solve this.

Upvotes: 0

Views: 65

Answers (2)

eric
eric

Reputation: 61

so I modified your HTML so that the inputs were both HTML5 number inputs, set it so that the results container would be initially empty, and fixed a some formatting.

<!DOCTYPE html>
<html>
    <head>
        <title>Audition</title>
    </head>
    <body>
        <h3>First Factors</h3>
        <div id="container">
            <label>Base Number: </label>
                <input id="baseNumber" type="number">
                <br />
            <label>Number of Factors: </label>
                <input id="numberOfFactors" type="number">
                <br />
            <button onClick="displayFactors();">Display Factors</button>
        </div>
        <div id="results">
        </div>
    </body>
</html>

as for the script I would go as follows:

first assign your input and output elements in the DOM to variables:

var baseNumHldr = document.getElementById("baseNumber");
var numOfFactsHldr = document.getElementById("numberOfFactors");
var resultsHldr = document.getElementById("results");

in the function called on the click event parse your input values (i have left out validation and error handling for simplicity), then get your factors from a function call, and finally display your results. since the results are being added by the script the span tags are not necessary and having the factors as an array allows for the join function to output a comma separated list.

function displayFactors() {
    var num = parseInt(baseNumHldr.value);
    var cnt = parseInt(numOfFactsHldr.value);
    var factors = getFactors(num, cnt);
    resultsHldr.innerHTML = 
         "<p>The first " + cnt + "factors of " + num + " are " + factors.join() + "</p>";
}

the getFactors function accepts two arguments the number to be factored, num, and the count of the factors to be returned, cnt. the function creates an array to return the length of cnt, preventing repeated array resizing. the for loop will run from 1 to the number unless the number of factors found meets the desired count, this is achieved using y as an index for the result array. when a value of x is a factor of the input number x will be assigned to the y index of the array, y will be incremented, and assuming x and y are less than the input parameters the loop will repeat.

function getFactors(num, cnt){
    var factArray = new Array(cnt);
    for (x = 1, y = 0; (x <= num) && (y < cnt); x++) {
        if (num % x == 0) {
            factArray[y] = x;
            y++;
        }
    }
    return factArray.filter(isDefined);
}

the return array in getFactors is filtered by the isDefined function below in case the input count of factors exceeds the number of actual factors allowing a simple join when displaying the output

function isDefined(val) {
    return val !== undefined;
}

also do not forget to reference or include the script with the html

Upvotes: 1

libertyernie
libertyernie

Reputation: 2686

I suppose you would start the loop at 1. Then, if any given number is not a factor (if it has a remainder), you want to keep the loop going, but not increment the loop variable.

I think that's the most notable part of this - usually, when people use for loops, there's a variable that increments on every iteration of the loop, but you also want another variable that you increment when you find a factor (or when you reach the number itself, because of course nothing above it can be a factor of it.)

var factors_found = 0;
for (var i=1; i<number; i++) {
    if (remainder == 0) {
        factors_found++;
        if (factors_found >= 3) {
            break;
        }
    }
}

In this case, the loop will exit when you reach the number OR when you find 3 factors, whichever comes first.

Of course, you'll want to store those factors somewhere. If you use an array, you could just check the length of that array to see how many you've found so far.

Upvotes: 0

Related Questions