简体   繁体   中英

Why is this program for finding Prime Factors of a number using Java not working?

I would like to know why this java program is not working to find the prime factors of a number. I have seen many solutions on this site and elsewhere but I want to know why this approach is not sufficient as it returns only 1 as an output? The first "if statement" handles numbers from 1 and lower to return -1 (invalid value), thanks.

public class PrimeFactors{

    public static void main(String[] args) {
        System.out.println(getPrimeFactors(4));
    }

    public static int getPrimeFactors(int number) {
        if (number <= 1) {
            return -1;
        }

        for (int i = 1; i <= number; i++) {
            if (number % i == 0) {
                return i;
            }
        }
        return number;
    }
}

The code you have here is returning the value of i, which you have set to 1. You don't have enough understanding of how you would find a prime number based on your code. No matter what you put into your method, getPrimeFactors will either return -1 or 1, because of how your code is set up. The remainder when a number is divided by 1 is always 0, therefore it is always true, which will just return 1. And if the number is less than or equal to 1, it will return -1. Return number is essentially dead code unless you fix the syntax. Hope this helps you out!

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