Finding factors of a given integer

前端 未结 14 1323
终归单人心
终归单人心 2020-12-16 19:52

I have something like this down:

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

Is there anything w

相关标签:
14条回答
  • 2020-12-16 20:17

    I got all the factors just fine with this (I just modified the algorithm in the question).

    int num1 = 120;
    
    for(int num2=1;num2<=num1;num2++)
    {
      if (num1%num2 != 0)
        System.out.println(num2);
    }
    
    0 讨论(0)
  • 2020-12-16 20:19

    Slightly modified solution: You can first check if variable x is divisible by variable y. If yes, we will count 1 and will repeat this process. For the loop counter, x/y is used and you should check x>0 to avoid repetition when x becomes zero but loop is not finished yet.

       public class Factor {
    
        public static void main(String[] args) {
    
            int x = 48;
            int x1 = x;
            int y = 2;
            int k = x / y;
            int j = 0;
            for (int i = 1; i < k; i++) {
                if ((x % y) == 0 && x > 0)
                    j++;
                x = x / 2;
            }
            System.out.println(+x1 + " is a factor of " + y + " for " + j
                    + " times.");
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题