Finding factors of a given integer

前端 未结 14 1373
终归单人心
终归单人心 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 19:52

    In order to find the factors of a given number, you only need to check upto the square root of the given number.

    For example, in order to find the factors of 6, you only need to check till 2.45 (√6). The factors of 6 will be 1 and 2, and their converse numbers, i.e. 3 and 6.

    I have made a program that determines the factors of a given number and displays them. Here is the necessary code:

        Scanner input = new Scanner(System.in);
    
        System.out.print("Enter integer: ");
        long num = input.nextLong();
    
        for(long i = 1; i <= Math.sqrt(num); i++) {
            if(num % i == 0) {
                System.out.println(i);
                if(i != num/i) {
                    System.out.println(num/i);
                }
            }
        }
    

    You just need this program to find the factors of a given number. However, if you want to take it a step further and display the factors arranged in ascending order, then the necessary code is as follows:

        Scanner input = new Scanner(System.in);
    
        System.out.print("Enter integer: ");
        long num = input.nextLong();
    
        ArrayList list1 = new ArrayList<>(), list2 = new ArrayList<>();
    
        long currentTime = System.currentTimeMillis();
    
        for(long i = 1; i <= Math.sqrt(num); i++) {
            if(num % i == 0) {
                list1.add(i);
                if(i != num/i) {
                    list2.add(num/i);
                }
            }
        }
    
        int n1 = list1.size() - 1;
        int n2 = list2.size() - 1;
    
        for(int i = 0; i <= n1; i++) {
            System.out.println(list1.get(i));
        }
    
        for(int i = n2; i >= 0; i--) {
            System.out.println(list2.get(i));
        }
    

    What this does: This program stores the factors of the number upto the number's square root in one list (list1), and the converse of these numbers in another list (list2). It then prints the elements of both lists (as shown).

提交回复
热议问题