EDW749

Loops Galore (primefact)
Summer 2006 - Dr. Roger Webster
 

Goals
- problem solving
- to use a for loop

Overview
For this lab, you will write a Java program called primefact that will compute the prime factors for all integers between two integers greater than or equal to 2 provided by the user. Prime factors of 84 are 2 x 2 x 3 x 7

Choose good variable names. Use functions and parameters when appropriate. Write descriptive and precise comments including at least one for each of your functions.

Prime Factors Specification (primefact)
The input will be two integers each greater than or equal to 2. Your program will print the prime factors of each integer between those two values. The prime factors are the prime numbers that divide evenly into a number. They should be displayed for each value as shown in the example. If the starting or ending value is not at least 2, print an error message and stop. Note that values with more than 9 digits may not be read or stored properly as integers.

We know that if there is no remainder when a divisor divides a number, the divisor "evenly divides" the number. If divisor evenly divides a number and divisor is prime, divisor is one of its prime factors. Therefore, print it and divide number by it. If you start looking with 2, you'll print only prime factors.

This program is more complex than others you've written. But if you develop it using iterative enhancement, you can do it. It's easier than it looks especially when you use functions that each do one thing well.

Hints
- think about what happens for 42 - walk through the algorithm by hand
- start with a for loop to just print the values between start and stop

   for (num = start; num <= stop; num++) {
      // stuff inside the loop
   }
- keep a count of the number of prime factors in a number; this will help you put the x's between the factors
- write a function to compute the prime factors of one number
- write a function that returns whether or not (bool) a divisor evenly divides a number;
   your function from the divides assignment is a handy start
- realize that a function must be declared before another function can call it;

Example Input and Output

Starting value (at least 2): 57
Ending value (at least 2): 65
Prime factors for numbers between 57 and 65
57 = 3 x 19
58 = 2 x 29
59 = 59
60 = 2 x 2 x 3 x 5
61 = 61
62 = 2 x 31
63 = 3 x 3 x 7
64 = 2 x 2 x 2 x 2 x 2 x 2
65 = 5 x 13

Another Example Input and Output

Starting value (at least 2): 4
Ending value (at least 2): 1
Values must be at least 2 rather than 4 and 1.

Basic Algorithm:

 // prints the prime factors of a number

function primeFactorsOf (int x)

{

  int divisor = 2;

  while (x > 1)

  {

                if (evenlyDivides (x, divisor))

{

                      print divisor;

                      x = x / divisor;

                }

else

                    divisor = divisor + 1;

  }

}