Monday, December 30, 2013

Greatest Common Divisor and Least Common Multiple Java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class mygcdlcm extends JFrame implements ActionListener
{   JButton jbgcd= new JButton("GCD");
    JButton jblcm= new JButton("LCM");
    JLabel jl1 = new JLabel("Number 1 ");
    JLabel jl2 = new JLabel("Number 2 ");
    JLabel jl3 = new JLabel("Result = ");
    JTextField jt1=new JTextField(10);
    JTextField jt2=new JTextField(10);
    JTextField jt3=new JTextField(10);
    public mygcdlcm()
    {   super("GCD LCM");                
        setSize(200, 200);
        jbgcd.addActionListener(this);   
        jblcm.addActionListener(this);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel pane = new JPanel();
        pane.setLayout(new GridLayout(4,2));
        pane.add(jl1);    pane.add(jt1);
        pane.add(jl2);    pane.add(jt2);
        pane.add(jl3);    pane.add(jt3);
        pane.add(jbgcd); pane.add(jblcm);
        jt3.setEditable(false);       
        setContentPane(pane);
        setVisible(true);
    }
    public void actionPerformed(ActionEvent e)
    {  int n1,n2,i,sn,ln;
       n1=Integer.parseInt(jt1.getText());
       n2=Integer.parseInt(jt2.getText());
       sn= n1>n2 ? n2 : n1;
       ln= n1>n2 ? n1 : n2;
       if(e.getSource()==jbgcd)
       {  for(i=sn;i>=1;i--)
              if(n1%i==0 && n2 %i==0) break;
          jt3.setText(i+"");
      jl3.setText("GCD");
       }
       if(e.getSource()==jblcm)
       {  for(i=ln;i<=n1*n2;i++)
              if(i%n1==0 && i%n2==0) break;
          jt3.setText(i+"");
      jl3.setText("LCM");
       }
    }
    public static void main(String[] arguments) {
        mygcdlcm rb = new mygcdlcm();
        rb.show();
    }
}


No comments:

Post a Comment