[ANU] [DCS] [COMP2100/2500] [Description] [Schedule] [Lectures] [Labs] [Homework] [Assignments] [COMP2500] [Assessment] [PSP] [Java] [Reading] [Help]
COMP2100/2500
Homework 2Exercise 1
Continue recording all time you spend on COMP2100/2500. Use a fresh Time Recording Log form each week. Same with the Weekly Time Use Summary. This will be part of the homework every week from now on.
Exercise 2
Write the following program, making a note of how long it takes you to complete it, and also of how many non-blank lines of code you end up with.
If you want to get a headstart on the PSP, try following the Initial PSP described in Lecture 4 and Lab 1 as you write this program.
Write a Java program (in a class Factors) that repeatedly prompts the user for an integer and then prints out the complete prime factorisation of that integer, with the factors in ascending order.
The program should stop when it reads an integer that is less than or equal to 1. You do not have to do any other data checking. In other words, you may assume that the user will type an integer, and it's OK if your program crashes if they type other stuff.
Here is a sample run of the program. User input is in blue, system output in black. Your final output should be formatted exactly like this:
comp2100@partch java Factors > 15 15 = 3 * 5 > 180 180 = 2 * 2 * 3 * 3 * 5 > 1999 1999 = 1999 > 2000 2000 = 2 * 2 * 2 * 2 * 5 * 5 * 5 > 2001 2001 = 3 * 23 * 29 > 2002 2002 = 2 * 7 * 11 * 13 > 2003 2003 = 2003 > 0 GoodbyeWhen you have completed this program, test it on a few numbers, large and small, until you would be prepared to stake your reputation on its correctness. Print out a copy of the source code, and store it securely in your lab notebook.
Suggestion: Use at least one procedure other than main().
Hints:
It makes things a lot simpler when you realise that if you search for factors in increasing order, you will only ever find prime factors. So you don't have to test if the factors are prime. (Maths students: Prove this!)
Reading from the keyboard is much easier in Java 1.5 than it was in earlier versions. Take a look at the documentation for class Scanner, particularly the methods nextInt() and hasNextInt().
Extension task: Think about the efficiency of your program. Would it be more efficient only to test primes? How could you do that without wasting more running time checking which numbers are primes? What if you just test odd numbers (since there are no even primes after 2)? Any other ideas?
[ANU] [DCS] [COMP2100/2500] [Description] [Schedule] [Lectures] [Labs] [Homework] [Assignments] [COMP2500] [Assessment] [PSP] [Java] [Reading] [Help]
Copyright © 2005, Ian Barnes, The Australian National University
Version 2005.1, Monday, 14 February 2005, 11:04:44 +1100
Feedback & Queries to
comp2100@cs.anu.edu.au