Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Java Code Help!! Using recursion to determine prime number and factors

1. ## Java Code Help!! Using recursion to determine prime number and factors

So I have this algorithm and it is driving me insane. What I have to do is calculate the factors of a given long number and display the factors and determine if the given long number is a prime number or not. For me, this algorithm makes sense but for Java, it doesnt lol...so I am posting my code so you guys can help me out! I am supposed to use recursions to determine if the number is prime or not. Any help will be awesome! Thanks!

[CODE]

int factor(long inputNumber)
{
for (int tracker = 1; tracker <= (inputNumber/2); tracker++)
{
if (inputNumber % tracker == 0)
{
counter++;
factor(inputNumber);
}
else
{
factor(inputNumber);
}
}
return counter;
}

String primefactor(long input)
{
long factors = factor(input);
if(factors > 2)
{
return String.valueOf(factors)+" = prime!";
}
else
{
return String.valueOf(factors)+" = not prime!";
}
}

[CODE]

• I believe the following code will be helpful:

Code:
```public class Main {

private long counter = 0;
private long count = 0;

public void primefactor(long input, long divident)
{
if (input == 0)
{
System.out.print("0 can be divided to any x real number, because 0 * x = 0");
}
if (divident <= count)
{
if (divident == 1)
{
System.out.print("1 ");
counter++;
if (input != 1)
{
primefactor(input, divident + 1);
}
}
else if (count % divident == 0)
{
if ((input % divident == 0))
System.out.print(divident + " ");
counter++;
while (input % divident == 0)
{
input /= divident;
}
primefactor(input, divident + 1);
}
else
{
primefactor(input, divident + 1);
}
}
}

public String primefactor(long input) {
count = input;
primefactor(input, 1);
System.out.println();
return (counter == 2) ? ("Prime") : ("Not Prime");
}

public Main()
{}

public static void main(String[] args) {
// TODO code application logic here
Main m = new Main();
Scanner scanner = new Scanner(System.in);
long input = scanner.nextLong();
System.out.println(m.primefactor(input));
}
}```

• ## Users who have thanked DistantJob for this post:

favelam (02-14-2011)

• ## I did the Prime part but still working on factors part

primeRecursion

Code:
```import java.util.Scanner;

public class primeRecursion {

public static void main(String[] args) {

System.out.print("Enter a number: ");
int input = new Scanner(System.in).nextInt();

System.out.println("Result: "+isPrime(input, input - 1));
}

//input is user's input; tracker is "input-1"
public static boolean isPrime(int input, int tracker) {
if (tracker <= 2) {
return true;
}

if (input % tracker != 0) {
return isPrime(input, tracker - 1);
} else {
return false;
}

}
}```

• ## Users who have thanked parrygill for this post:

favelam (02-14-2011)

• My solution solves the factor part too...

• ## Did the factors too

primeRecursion.java

Code:
```import java.util.Scanner;

public class primeRecursion {

public static void main(String[] args) {

System.out.print("Enter a number: ");
int input = new Scanner(System.in).nextInt();

if(isPrime(input, input - 1)){
System.out.println("Input is a prime number");
} else {
System.out.println(" factors\nInput isn't a prime number.");
}
}

//input is user's input; tracker is "input-1"
public static boolean isPrime(int input, int tracker) {
if (tracker <= 2) {
return true;
}

if (input % tracker != 0) {
return isPrime(input, tracker-1);
} else {
doFactors(input, tracker);
return false;
}
}

public static void doFactors(int input, int tracker) {
if (tracker <= 1) {
System.out.printf(" %d", 1);
} else {
if (input % tracker == 0) {
System.out.printf(" %d", tracker);
}
doFactors(input, tracker - 1);
}
}
}```

• ## Users who have thanked parrygill for this post:

favelam (02-14-2011)

• that's good, I was working on my solution, anyways now "favelam" is having two solutions.

• You guys are amazing!!!! It worked perfectly just have to change a the code so it displays in a textfield instead of the console but other than that its awesome! Thanks!!

• Ok so I came across some buggs...When I input 2 the first time it tells me its a prime number...when I input a different number( doesnt matter if it is prime or not) then I input 2 again, it tells me that 2 is not a prime number and it keeps telling me that until I close the program...here is all my code....this is a GUI asking the user to input a number in...

Code:
```import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class prime extends javax.swing.JFrame implements ActionListener
{
//variables

private JPanel jPanel;
private JPanel buttonJPanel;
private JTextField inputJTextField;
private JButton factorJButton;
private JLabel outputJLabel;
private long counter = 0;
private long count = 0;

//end of variable decleration
public prime()
{
initComponents();
disableAlpha();
}

private void initComponents()
{
jPanel = new JPanel();
inputJTextField = new JTextField();
buttonJPanel = new JPanel();
factorJButton = new JButton();
outputJLabel = new JLabel();

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("Prime Factorization");
setMinimumSize(new Dimension(600, 150));
setResizable(false);

jPanel.setLayout(new GridLayout(3, 0));
inputJTextField.setText("");

factorJButton.setText("Factor!");
{

public void actionPerformed(ActionEvent evt)
{
factorJButtonActionPerformed(evt);
}
});

outputJLabel.setText("");
outputJLabel.setForeground(Color.RED);

{

public void actionPerformed(ActionEvent evt)
{
}
});
pack();
}

{
System.exit(0);
}

private void factorJButtonActionPerformed(ActionEvent evt)
{
inputJTextField.getText();
long inputNumber = Long.valueOf(inputJTextField.getText());
if (inputNumber <= 1)
{
outputJLabel.setText(String.valueOf(inputNumber) + " is not a valid input. Enter a number greater than 1 and less than " + String.valueOf(Long.MAX_VALUE));
} else
{
String primeFactorOutput = primefactor(inputNumber);
outputJLabel.setText(primeFactorOutput);
}
}

private void disableAlpha()
{
for (char c = ':'; c <= '~'; c++)
{
inputJTextField.getInputMap().put(KeyStroke.getKeyStroke(c),
"none");
}
for (char c = '\0'; c < '0'; c++)
{
inputJTextField.getInputMap().put(KeyStroke.getKeyStroke(c),
"none");
}
}

public void primefactor(long input, long divident)
{
if (divident <= count)
{
if (divident == 1)
{
System.out.print("1 ");
counter++;
if (input != 1)
{
primefactor(input, divident + 1);
}
} else if (count % divident == 0)
{
if ((input % divident == 0))
{
System.out.print(divident + " ");
}
counter++;
while (input % divident == 0)
{
input /= divident;
}
primefactor(input, divident + 1);
} else
{
primefactor(input, divident + 1);
}
}
}

public String primefactor(long input)
{
count = input;
primefactor(input, 1);
System.out.println();
return (counter == 2) ? ("Prime") : ("Not Prime");
}

public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(new Runnable()
{

public void run()
{
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
prime myPrime = new prime();
int x = (screen.width - myPrime.getWidth()) / 2;
int y = (screen.height - myPrime.getHeight()) / 2;
myPrime.setBounds(x, y, myPrime.getWidth(), myPrime.getHeight());

myPrime.setVisible(true);
myPrime.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}

public void actionPerformed(ActionEvent ae)
{
throw new UnsupportedOperationException("Not supported yet.");
}
}```

• Fixed it! I had taken out:

Code:
`counter = 0;`
after I ran recursion

If you guys find any more bugs, let me know!

• There is a member called counter, which is always increased when you call the method. If you want to use this repeatedly, you must set it to 0, so instead of

Code:
```   public String primefactor(long input) {
count = input;
primefactor(input, 1);
System.out.println();
return (counter == 2) ? ("Prime") : ("Not Prime");
}```
you should have:

Code:
```    public String primefactor(long input) {
count = input;
primefactor(input, 1);
System.out.println();
long counterTemp = counter;
counter = 0;
return (counterTemp == 2) ? ("Prime") : ("Not Prime");
}```

• Excellent, nice job favelam.

• Or I can assign 0 to counter after the recursion has been executed and has displayed the output.

Code:
```{
String primeFactorOutput = primefactor(inputNumber);
outputJLabel.setText(primeFactorOutput);
counter = 0;
}```
which is under the action performed when you press factor. Since you will have to press the factor button again, we can just make counter = 0 at the end of the JButton action performed code.

Code:
```private void factorJButtonActionPerformed(ActionEvent evt)
{
inputJTextField.getText();
long inputNumber = Long.valueOf(inputJTextField.getText());
if (inputNumber <= 1)
{
outputJLabel.setText(String.valueOf(inputNumber) + " is not a valid input. Enter a number greater than 1 and less than " + String.valueOf(Long.MAX_VALUE));
} else
{
String primeFactorOutput = primefactor(inputNumber);
outputJLabel.setText(primeFactorOutput);
counter = 0;
}
}```

• Yes, what you say is a working idea, but it's against the policy of separation. While now you are implementing your data parser and GUI methods in the same class, later you will start to separate your engine from the GUI and counter is part from your engine.

Later you might want to make a new version from this project (I know this is an exercise, but let's pretend this is a project which will be updated later). Since counter is storing logical part of your data your project should be built in a way to help your future self when you'll have to separate your code into two parts. This means that whatever is logical should be done in your methods, which handle the logical part. Of course there are exceptions from this doctrine (as always), but here you have no reason to handle this logical operation directly in your event handler.

So, in short, you had a good idea, but there is a general policy of separating the GUI from the engine, so, the only reason counter = 0 is better in primefactor is that this way your project will be conform to the general ideas of programming.

• Also, if you want to use primefactor from more places you'll have to put counter = 0; everywhere if this setting is not done in the logical part, while, if you put counter = 0; into primefactor, you will never encounter the problem of repetitive usage (because you've already finded the solution and it's at the best possible way).

• Yes I understand what you are saying. Separating the code into a GUI.java for the GUI and the main.java for the main and the same process for other methods which will be easier since you could use the same methods or classes in different programs. At this moment I just wanted to finish the main idea of the program then make it nicer after. i hadn't thought about separating the code until you mentioned it and it will look better than how I have it set up right now. I know that once my code is starting to reach 1900+ lines, its a big indicator that I should start separating the GUI from the methods and main program lol

Thank you for you help and ideas!

•
Page 1 of 2 12 Last

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•