TWiki> Main Web>MultimediaProgramming2013>Multimedia2013Lab3 (2013-02-18, JimSkon)

# Lab 3 - Javascript Prime Calculator

### Goal

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

### Step 1 - Check if a number is prime

Create a page with an input field, an output text area, and a button called "Check Prime". When a number n is entered, and the button is pressed, have the system determine whether the number is prime and in the text area write either:

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.

### Step 2 - build a factor table

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:

###### Number: 448
# 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).

### Step 3 - prime factorization

##### This step is:

• Required for ALL students who are in or have taken Data Structures
• Optional for others (+20% extra credit)
Add a third button call "Show prime factorization". This will show the prime factorization of the number (e.g. it will show the set of primes that when multipled togetherequal this number.

Example:

###### Number: 448Prime factorization: 2 * 2 * 2 * 2 * 2 * 2 * 7

Alternately, you could display the factorization as a polynomial:

###### Number: 448Prime factorization: 26 x 71

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.
import java.util.ArrayList;
import java.util.List;

public class PrimeFactors {
public static List<Integer> primeFactors(int number) {
int n = number;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n; i++) {
while (n % i == 0) {