How to find the factors of a number with for loops? [closed]

余生长醉 提交于 2019-12-25 17:19:21

问题


Hey I need some help with my AP Comp Sci homework. In the assignment I need to print the factors of a passed variable, z. This is what I've gotten so far in my method

public static void printFactors(int z) {
    for(int x=1; x<=z; x++) {
        if(z%x.......) {
            System.out.println(x);
        }
    }
}

How would I go about finishing this? Or am I even on the right track? Thanks!


回答1:


As your question, you want to get ALL factors, I might think, you want the full list, but distinct factors of an integer.

So, you can only iterates the integer x from 1 to sqrt(z), but sqrt itself is too slow, and you can loop x until x*x > z, see the for loop below.


More, you should take care that if z % x == 0

for example: z = 18, x =3, z % x = 0

then z / x must be also a factor, too! It should be output.

but to avoid duplicated factors produced, if z == x * x, then x == z / x, the two factors x and z/x is duplicate, it should only be output once.

This is a classical algorithm issue, and this implemetation is the generally used one, which with time complexity O(sqrt(z)).


See the code:

public static void printFactors(int z) {
    for(int x=1; x * x <= z; x++) {
        if(z % x == 0) {
            System.out.println(x);
            if(x * x != z) System.out.println(z / x);
        }
    }
}

Have a try!




回答2:


  public static void printFactor( int z){
      for(int i = 1; i < sqrt(z); i++){
         if(z%i == 0){ system.out.println(i);}
      }
  }

The == 0 is to make sure there is no remainder because the factor has to be an number with no decimal (of course)

The sqrt is because you would be checking the same numbers if you went passed that value.




回答3:


public static void printFactors(int z) {
    for(int x=1; x * x <= z; x++) {
        if(z % x == 0) {
            System.out.println(x);
            if(x * x != z) System.out.println(z / x);
        }
    }
}


来源:https://stackoverflow.com/questions/25799235/how-to-find-the-factors-of-a-number-with-for-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!