Programming Exercise 3
Loops
1. Write a program to determine if a number is a prime number. The number should be entered by a user.
Hint, use the modulus operator to help determine if the number is prime.
5 % 4 = 1
4 % 2 = 0
17 % 5 = 2
The modulus operator, % returns the remainder from integer division.
Think carefully about what numbers you must divide the candidate by before you know it is prime. Try to determine if the number is prime with the minimum number of modulus operations.
2. Expand your program from part 1 to find all the prime numbers between 2 and a integer entered by the user. The numbers should be printed out to the screen.
3. Write a program that determines and prints out the prime factors of an integer. For example the prime factors of 175 are
5
5
7
4. From the Dr. Math website for calculating square roots by hand:
A much better method was known to Heron (of Alexandria), who is believed to have lived between 150 BC and 250 AD.
He noted that if you pick a_1 as a random guess for a possible value of sqrt(n) then
a_2 = [a_1 + (n/a_1)]/2
will be a better approximation. Similarly,
a_3 = [a_2 + (n/a_2)]/2
will be a better approximation than a_2. These approximations form a sequence of numbers {a_i} that converge very rapidly to sqrt(n). Calculate the square root for a number entered by the user to within .0001 of the correct answer. You can check the accuracy of your answer, squaring it, and compare it to n. Compare your results with the actual square root.
5. Write a program to simulate a random walk. A random walk is a series of steps or movements that are determined by chance. Assume the walk starts at the origin. Each turn or step can be up to 2 units in the horizontal direction and 2 units in the vertical direction.
To pick a random number use the random method in the Math class. The code to get 1 random number is
double dx;
dx = Math.random();
Math.random() returns a random double (floating point number) value with uniform
distribution between 0 and 1. Run a simulation of 1000 steps or turns. Run 1000
of these simulations. Compute and print:
The average distance from the origin at the end of the walk.
The standard deviation of the distance from the origin at the end of the walk.
The max distance from the origin by a single simulation.
The min distance from the origin by a single simulation.