This week's giveaway is in the Android forum. We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line! See this thread for details.

Write a program that asks the user for an integer and then prints out all its factors. For example, when the user enters 150, the program should print
2, 3, 5, 5

I have

This works for 150, but for a number like 6, it will print 2, 2
I don't know what I'm doing wrong or how to fix it

Theresa Marlin wrote:
This works for 150, but for a number like 6, it will print 2, 2
I don't know what I'm doing wrong or how to fix it

You have a pretty complex maneuver here...

Basically, you are doing the division to find the "other" divisor (the number that when multiplied to the divisor will yield the orig number) and then checking this "other" divisor to see if it is a divisor. The problem with this is... if the "other" divisor is not a whole number (which for non-factors, it isn't), it will round down. This rounding of the "other" divisor, can cause it to be a valid divisor, when testing it.

Why so complex? Why not test the divisor directly? What's wrong with "number % divisor"?

Thank you so much for your help! I don't know why I was doing it the way I did, for some reason I thought that that was the only way it would work with it being integer division.
Thanks again!

You have a test for number > 0 inside a loop while (number > 1). I hardly think that test is necessary.

I have been teaching undergraduates today and I been telling them off for using the wrong hardware. Then I showed them a pencil and a large eraser, which I think is the equipment you ought to use now, too
Take a number, any number, well 6, take a divisor, any divisor, well 2, and work out what number % (number / divisor) will come to. Can you concoct a simpler test which will work?
Now work out what the test after the else if does. What would happen if you simplify that test? Does that second test do anything useful at all?

Lose the bit about if (number == 1) Move the System.out.println() call after the end of your loop.

Theresa Marlin
Ranch Hand

Joined: Sep 23, 2009
Posts: 49

posted

0

Thank you for your comments. I fear you are very right about my need to use a pencil and eraser. I had been trying to use my interactions window to do all the tests separately, but it was getting a bit confusing. I have amended my code.
Thanks again!