Alex Rivera | Logout

Finding factors of a given integer

Asked 2011-12-27T16:49:11.060
13

I have something like this down:

int f = 120;
for(int ff = 1; ff <= f; ff++){
    while (f % ff != 0){            
}

Is there anything wrong with my loop to find factors? I'm really confused as to the workings of for and while statements, so chances are they are completely wrong.

After this, how would I go about assigning variables to said factors?

Edit
Report

2 Answers

2

There's nothing wrong with your for loop, but a while loop is the wrong thing to be using here. The logic of your for loop is:

  • Set ff to 1.
  • Keep going while ff <= f.
  • After you've done everything in the for loop, add 1 to ff.

This looks like it is exactly as you want.

The while loop isn't right, though. It will continue to do whatever code you write there for as long as ff is a factor of f, so unless you change them in the while code, you'll get an infinite loop. However, changing that to an if statement will give you what you want.

Since you're checking for factors, you don't actually need to check all possibilities up to f - only up to the square root of f. Whenever you find that ff is a factor, output both ff and f/ff as factors, unless f is a sqare number.

answered 2011-12-27T21:34:30.733
0

It looks like you are not going to do something with either f or ff in your while loop? If so, the expression f%ff != 0 is either false (and then it will go to the next in the for loop), or it is true, and it will end up in an infinite loop.

Are you sure you need the while like this?

answered 2011-12-27T16:52:40.200

Your Answer