简体   繁体   English

编写递归方法来查找传入数字的质因数

[英]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.如果传入的数字是质数,则应返回字符串“Prime”。 I give the program the following in-put我给程序以下输入

FindPrime p10 = new FindPrime(408);

i'm supposed to get: 2x2x2x3x17 but the output is:我应该得到:2x2x2x3x17 但 output 是:

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我不知道 go 还能去哪里

That is because:那是因为:
First, in the else statement, why did you divide?( findPrime(num/div); )首先,else语句中,为什么要除?( findPrime(num/div); )
Second, no idea what if(num == 1) means其次,不知道if(num == 1)是什么意思
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
            
        }       
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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