-1

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;
    }
}
Abhinav
  • 530
  • 8
  • 21
Tunde
  • 31
  • 7
  • 3
    Possible duplicate of [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Hovercraft Full Of Eels Nov 10 '18 at 03:20
  • 1
    Please see the [How to Ask](https://stackoverflow.com/help/how-to-ask) page. Get out a pencil and paper and "play computer" for a moment: what's actually happening? – Dave Newton Nov 10 '18 at 03:21
  • 1
    It seems that you have a fundamental misunderstanding of how `return` works. I advise that you refer to a Java tutorial and look up either print statements or arrays, as they may provide a good alternative to the inner return statement depending on what you want your output to be. – Andrew Fan Nov 10 '18 at 03:23

1 Answers1

3

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!

Excel
  • 75
  • 8