Finding factors of a given integer

前端 未结 14 1321
终归单人心
终归单人心 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: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.");
    
        }
    }
    

提交回复
热议问题