Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    8
    Thanks
    3
    Thanked 0 Times in 0 Posts

    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]

  • #2
    New Coder
    Join Date
    Feb 2011
    Posts
    48
    Thanks
    1
    Thanked 2 Times in 2 Posts
    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)

  • #3
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    7
    Thanks
    0
    Thanked 3 Times in 3 Posts

    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)

  • #4
    New Coder
    Join Date
    Feb 2011
    Posts
    48
    Thanks
    1
    Thanked 2 Times in 2 Posts
    My solution solves the factor part too...

  • #5
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    7
    Thanks
    0
    Thanked 3 Times in 3 Posts

    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)

  • #6
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    7
    Thanks
    0
    Thanked 3 Times in 3 Posts
    that's good, I was working on my solution, anyways now "favelam" is having two solutions.

  • #7
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    8
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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!!

  • #8
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    8
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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 JMenuBar menuJMenuBar;
        private JMenu fileJMenu;
        private JMenuItem quitJMenuItem;
        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();
            menuJMenuBar = new JMenuBar();
            fileJMenu = new JMenu();
            quitJMenuItem = new JMenuItem();
    
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setTitle("Prime Factorization");
            setMinimumSize(new Dimension(600, 150));
            setResizable(false);
    
            jPanel.setLayout(new GridLayout(3, 0));
            inputJTextField.setText("");
            jPanel.add(inputJTextField);
    
            factorJButton.setText("Factor!");
            factorJButton.addActionListener(new ActionListener()
            {
    
                public void actionPerformed(ActionEvent evt)
                {
                    factorJButtonActionPerformed(evt);
                }
            });
    
            buttonJPanel.add(factorJButton);
            jPanel.add(buttonJPanel);
    
            outputJLabel.setText("");
            outputJLabel.setForeground(Color.RED);
            jPanel.add(outputJLabel);
    
            getContentPane().add(jPanel, BorderLayout.CENTER);
            fileJMenu.setText("file");
            quitJMenuItem.setText("quit");
            quitJMenuItem.addActionListener(new ActionListener()
            {
    
                public void actionPerformed(ActionEvent evt)
                {
                    quitJMenuItemActionPerformed(evt);
                }
            });
            menuJMenuBar.add(fileJMenu);
            fileJMenu.add(quitJMenuItem);
            setJMenuBar(menuJMenuBar);
            pack();
        }
    
        private void quitJMenuItemActionPerformed(ActionEvent evt)
        {
            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.");
        }
    }

  • #9
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    8
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Fixed it! I had taken out:

    Code:
    counter = 0;
    after I ran recursion

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

  • #10
    New Coder
    Join Date
    Feb 2011
    Posts
    48
    Thanks
    1
    Thanked 2 Times in 2 Posts
    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");
        }

  • #11
    New Coder
    Join Date
    Feb 2011
    Posts
    48
    Thanks
    1
    Thanked 2 Times in 2 Posts
    Excellent, nice job favelam.

  • #12
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    8
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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;
          }
       }

  • #13
    New Coder
    Join Date
    Feb 2011
    Posts
    48
    Thanks
    1
    Thanked 2 Times in 2 Posts
    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.

  • #14
    New Coder
    Join Date
    Feb 2011
    Posts
    48
    Thanks
    1
    Thanked 2 Times in 2 Posts
    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).

  • #15
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    8
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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 LastLast

    Posting Permissions

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