/*
 * FactorsPanel.java
 *
 * Created on 1 de septiembre de 2008, 23:33
 */



import java.math.*;

/**
 *
 * @author  Sergio
 */
public class FactorsPanel extends javax.swing.JPanel {

    
    /* -------------------------------------------------------------------------
     *           METODO QUE TRANSFORMA UN NUMERO A FORMATO CIENTIFICO 
     * -----------------------------------------------------------------------*/
    public static String sci(String number, int numDec){
        String sciNumber = "0";
        sciNumber = number.substring(0, 1) + "." 
                + number.substring(1, numDec+1)
                + " * 10^("+ String.valueOf(number.length()-1) +")";
        return sciNumber;
    }//-------------------------------------------------------------------------
    
    /* -------------------------------------------------------------------------
     *          METODO QUE CALCULA EL FACTORIAL DE UN NUMERO ENTERO
     * -----------------------------------------------------------------------*/
    public static String factorial(int n){
        BigInteger nfact = BigInteger.ONE;
        BigInteger aux;
        if(n!=0 && n!=1){
            for(int i=2; i<=n; i++){
                aux = new BigInteger(String.valueOf(i));
                nfact = nfact.multiply(aux);
            }
        }
        return nfact.toString();        
    }//-------------------------------------------------------------------------
    
    /* -------------------------------------------------------------------------
     *         METODO QUE COMPRUEBA SI UN NUMERO DADO ES O NO PRIMO
     *               Para ello utiliza el teorema de Wilson
     * -----------------------------------------------------------------------*/
    public static boolean primaly(int p){
        boolean prime;
        BigInteger factorialParcial = new BigInteger(factorial(p-1));
        factorialParcial = factorialParcial.add(BigInteger.ONE);
        if(factorialParcial.divideAndRemainder
                (BigInteger.valueOf(p))[1].equals(BigInteger.ZERO)){
            prime = true;
        }
        else{
            prime = false;
        }
        return prime;
    }//-------------------------------------------------------------------------
    
    
    /* -------------------------------------------------------------------------
     *         METODO QUE AVERIGUA LOS NUMEROS PRIMOS HASTA UNO DADO
     * -----------------------------------------------------------------------*/
    public static void primeSearch(int limit){
        System.out.println("Los numeros primos hasta "+limit+" son: ");
        for(int i=2; i<limit; i++){
            if(primaly(i)){
                System.out.println(i);
            }
        }
            
    }//-------------------------------------------------------------------------
    
    
    /* -------------------------------------------------------------------------
     *           METODO QUE BUSCA X NUMEROS CONSECUTIVOS NO PRIMOS
     * -----------------------------------------------------------------------*/
    public static int[] noPrime(int x){
        int[] result = new int[x];
        int encontrados=0; int num=2; int index=0;
        while(encontrados<x){
            if(!primaly(num)){
                System.out.print(num+" no es primo; ");
                encontrados++;
                result[index]=num;
                index++;
                
            }
            else{
                System.out.println(num+" si es primo.");
                System.out.println("Lo intentaremos a partir de "+ (num+1));
                index=0;
                encontrados=0;
                result = new int[x];
            }
            num++;
        }
        System.out.println("\nEncontrados "+x+
                " numeros consecutivos no primos: ");
        for(int i=0; i<x; i++){
            System.out.println(result[i]+" | ");
        }
        return result;
    }//-------------------------------------------------------------------------
    
    
    /* -------------------------------------------------------------------------
     *          METODO QUE DESCOMPONE UN NUMERO EN SUS FACTORES PRIMOS
     * ------------------------------------------------------------------------*/
    public static String primeFactors(int num){
        int cociente = num;
        String sol="";
        
        for(int i=2; cociente>1; i++){
            if(primaly(i)){
                if(cociente%i==0){
                    cociente = cociente/i;
                    sol = sol + String.valueOf(i) + " * ";
                    i--;
                }
            }
        }
        
        return sol;
    }
    
    //-------------------------------------------------------------------------
    
    
    /** Creates new form FactorsPanel */
    public FactorsPanel() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();

        setBackground(new java.awt.Color(255, 255, 255));
        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Factorizador de numeros", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11), new java.awt.Color(0, 0, 0))); // NOI18N

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Introduce aquí el número que deseas factorizar:");

        jLabel2.setText("(NOTA: Tu PC hace los cálculos, cuidado con números grandes)");

        jButton1.setText("Factorizar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel3.setText("Solución:");

        jLabel4.setText("(NOTA: El tiempo que tarda depende del numero introducido)");

        jTextPane1.setEditable(false);
        jScrollPane1.setViewportView(jTextPane1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1)
                .addGap(8, 8, 8)
                .addComponent(jLabel3)
                .addGap(4, 4, 4)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    
    jTextPane1.setText("Realizando cálculos. Espere, por favor.");
    try{
        if(!primaly(Integer.parseInt(jTextField1.getText()))){
            jTextPane1.setText(primeFactors
                    (Integer.parseInt(jTextField1.getText())));
        }
        else{
            jTextPane1.setText("El número "+
                    jTextField1.getText()+" es primo.");
        }
    }
    catch(Exception ex){
        jTextField1.setText(jTextField1.getText()+" no es un numero valido");
    }
    
}//GEN-LAST:event_jButton1ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration//GEN-END:variables

}

