0

Here is a starter program that prints prime factors of a supplied numbers as a string.It's quite buggy as the input 8 yields 1.2.4 when what i wanted is 1.2.2.2 and I don't understand why the return in line 32 (commented) is not executed.

```
//program to compute prime factors of a number
import javax.swing.JOptionPane;
import java.util.Arrays;
public class test {
public static void main(String[] args) {
int num;
for (int counter=0;counter<10;counter++){
String input=JOptionPane.showInputDialog("Enter a number.");
try{
num=Integer.parseInt(input);
}
catch(NumberFormatException nfe){
input=JOptionPane.showInputDialog("Invalid input. Enter an integer.");
num=Integer.parseInt(input);
}
System.out.println(calculateFactors("1.",num));
}
}
public static String calculateFactors(String list,int num){ /*list is passed to preserve the string during recursion*/
for (int i=2;i<=num;i++){
if(isPrime(num)){
list=list+Integer.toString(num)+"."; //why isn't this executed???
return list;
}
if(isPrime(i)){
if(num%i==0){
list=list+Integer.toString(i)+".";
num=num/i;
calculateFactors(list,num);
}
}
}
return list+Integer.toString(num);
}
static boolean isPrime(int num){
for(int i=2;i<num;i++){
if(num%i==0){
return false;
}
}
return true;
}
}
```

I am new to programming and recursion is confusing which is probably the reason for my problems. Any help and suggestions would be much appreciated.

*Edited 6 Years Ago by guyfrompluto*: n/a