- To build a simple application for computing prime numbers.
- Using Javascript with fields and tables

Create a page with an input field, an output text area, and a button called "** Check Prime**". When a number

- "The number
*n*is a prime number"

or

- "The number
*n*is not a prime number, it is divisable by*x*."

Where *n* and *x* are the actual numbers.

Use CSS to make the page look nice.

**Note**: A number *n* is divisable by *x* if:

*n* % *x* = 0

where % is the **mod** operator. The **mod** operation of *x* %* y* returns the remainder of dividing *x* by* y*.

Add a second button to the pages from above called "* show factors*". When this button is pressed build an attractive table showing a list of ALL the factors of the number types in, including 1 and the number itself. Actually generate an HTML table of the following general form:

# | Factor |
---|---|

1 | 1 |

2 | 2 |

3 | 4 |

4 | 7 |

5 | 8 |

6 | 14 |

7 | 16 |

8 | 28 |

9 | 32 |

10 | 56 |

11 | 64 |

12 | 112 |

13 | 224 |

14 | 448 |

The table should appear at the bottom of the page. if another another number is entered, and the button press, replace the table with the new one.

**Hint**: You can find the factor of *n* simply by doing a *n* % *x* on every *x *between 1 and *n*. This will require a loop ( **for** or **while**).

- Required for ALL students who are in or have taken Data Structures
- Optional for others (+20% extra credit)

Example:

Prime factorization: 2 * 2 * 2 * 2 * 2 * 2 * 7

Alternately, you could display the factorization as a polynomial:

Prime factorization: 2

Below some Java code (not JavaScript !) to do factorization (you will need to come up with a Javascript version). You won't need to use lists, simply create two arrays, one with the factors (like above) and another to keep count a of the number of times that factor was used. Thus you will end up with something like this: (this is NOT displayed by your program)

Index | Factor | Count |
---|---|---|

2 | 2 | 6 |

3 | 4 | 0 |

4 | 7 | 1 |

5 | 8 | 0 |

6 | 14 | 0 |

7 | 16 | 0 |

8 | 28 | 0 |

9 | 32 | 0 |

10 | 56 | 0 |

11 | 64 | 0 |

12 | 112 | 0 |

13 | 224 | 0 |

// Java Code to find the Prime Factorization of a number.importjava.util.ArrayList;importjava.util.List;publicclassPrimeFactors {publicstaticList<Integer> primeFactors(intnumber) {intn = number; List<Integer> factors =newArrayList<Integer>();for(inti = 2; i <= n; i++) {while(n % i == 0) { factors.add(i); n /= i; } }returnfactors; }

Topic revision: r4 - 2013-02-18 - JimSkon

Copyright &© by the contributing authors. All material on this collaboration platform is the property of the contributing authors.

Ideas, requests, problems regarding TWiki? Send feedback

Ideas, requests, problems regarding TWiki? Send feedback