简体   繁体   中英

How do I display the largest factor of an inputted number?

package Testing;

import java.util.Scanner;

public class test {

     public static void main (String[] args){
        Scanner scan1 = new Scanner(System.in);
        System.out.print("Input positive integer: ");
        int n = scan1.nextInt();

        for (int i = 2; i < Math.sqrt(n); i++){
            if (n % i == 0){
                System.out.print(n/i);
            }
        }

    }

}  

When I run this code it ends up printing the numbers 2510 whenever I input 50. What did I do wrong?

As was mentioned in the comments, you're very close, but you need to stop iterating after you find an answer. This can be done with the break keyword, which exits the innermost loop.

for (int i = 2; i < Math.sqrt(n); i++){
    if (n % i == 0){
        System.out.print(n/i);
        break;
    }
}

You have to stop when you find the first prime factor. And do not forget, that in your example Math.sqrt(n) is calculated every loop.

public static int getLargestFactor(int num) {
    for (int i = 2, max = (int)Math.sqrt(num); i <= max; i++)
        if (num % i == 0)
            return num / i;

    return num;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM