简体   繁体   中英

Writing a recursive method to find the prime factors of a number that is passed in

I have to write a recursive method to find the prime factors of a number that is passed in. The prime factors should be returned in a string in which the prime factors are separated by spaces, and ordered from smallest to largest, left to right. If the number passed in is prime, the string "Prime" should be returned. I give the program the following in-put

FindPrime p10 = new FindPrime(408);

i'm supposed to get: 2x2x2x3x17 but the output is:

2x2x2x3x4x4xprime number

Here is the program I have coded

public class FindPrime{
public int div = 2;

public FindPrime(int i) {
    System.out.println(i + " factorization:");
    findPrime(i);
    System.out.println();
}

public void findPrime(int num) {
    if(num == 1) {
        System.out.println("prime number");
        return;
    }
    else if(num % div == 0) {
        System.out.print(div + "x");
        findPrime(num/div);
    }
    else {
        div++;
        System.out.print(div + "x");
        findPrime(num/div);
        
    }       
}

}

Can someone please help? I don't know where else to go

That is because:
First, in the else statement, why did you divide?( findPrime(num/div); )
Second, no idea what if(num == 1) means
So this is what it should be:

    public int div = 2;
    public void FindPrime(int i) {
        System.out.println(i + " factorization:");
        findPrime(i);
        System.out.println();
    }

    public void findPrime(int num) {
        if(div == num) {// it's the base case
            System.out.print(div);
        }
        else if(num % div == 0) {
            System.out.print(div + "x");
            findPrime(num/div);
        }
        else {
            div++;
            //System.out.print(div + "x");// Why are you sure that it's going to divide?
            findPrime(num);//you pass in the number, not divide then pass it in
            
        }       
    }

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