Una forma sencilla y rápida de aprender JAVA, observando y deduciendo cómo se comporta el lenguaje a través de ejemplos prácticos.

Archivo del blog

lunes, 6 de diciembre de 2021

Cálculo de la cantidad de números primos contenidos en X.

En Netbeans se crea un JFrame y en modo diseño se añaden los siguientes componentes:

jButtonCalcular
jTextFieldNumeroX
jTextFieldResultado

jLabels varios para identificar tipos de datos que hay que añadir en los jTextFields.
jPanels varios para agrupar y facilitar la inserción de los componentes cuando trabajamos en modo diseño.


Código Java (CantidadPrimos.java):

package primosnum;

public class CantidadPrimos extends javax.swing.JFrame {

    public CantidadPrimos() {
        initComponents();
        this.setLocationRelativeTo(null);
    } 

    private void initComponents() { ... *Código generado automaticamente por NetBeans ... }

    private void jButtonCalcularActionPerformed(java.awt.event.ActionEvent evt) {                                                
        calcular();
    }                                               

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CantidadPrimos().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButtonCalcular;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField jTextFieldNumeroX;
    private javax.swing.JTextField jTextFieldResultado;
    // End of variables declaration                   

    private void calcular() {

        double x = Double.parseDouble(jTextFieldNumeroX.getText());
        double a0 = (2 * x + Math.pow(-1, x) - 1) / 6;  //* usar BigInteger¿?  
        double a1 = Math.ceil(a0) - 1;
        double b = (-1 + (Math.sqrt(-2 + 3 * a0))) / 3;
        double k = 0, suma = 0;
        double numerador, denominador, resultado;
        for (int j = 8; j < a1; j++) {
            for (int i = 1; i < b; i++) {
                numerador = 4 * j - Math.pow(-1, j) + ((2 * i + 1) * Math.pow(-1, i + j)) + ((2 * i - 1) * Math.pow(-1, i)) - (12 * i * i) + 5;
                denominador = 12 * i + 6 - (2 * Math.pow(-1, i));
                k += funcionEit(numerador / denominador);
            }
            suma += funcionEit(k);
            k = 0;
        }
        resultado = Math.ceil((2 * x + Math.pow(-1, x) - 6 * suma + 5) / 6);
        jTextFieldResultado.setText("" + (int) resultado);
    }

    private double funcionEit(double x) {
        return ((x <= 0) || (x - Math.floor(x) > 0) ? 0 : 1);
    }

}



Resultado:







 

 

 

 

 

 

 

 

 

 

 

*Código generado automáticamente por NetBeans

    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldResultado = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldNumeroX = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jButtonCalcular = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Barlow Condensed Medium", 1, 36)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 0, 204));
        jLabel1.setText("Números Primos en X");

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel3.setFont(new java.awt.Font("Barlow Condensed Medium", 0, 18)); // NOI18N
        jLabel3.setText("Cantidad de primos que contiene X");

        jTextFieldResultado.setEditable(false);
        jTextFieldResultado.setFont(new java.awt.Font("Barlow Condensed Medium", 0, 36)); // NOI18N
        jTextFieldResultado.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        jLabel2.setFont(new java.awt.Font("Barlow Condensed Medium", 0, 18)); // NOI18N
        jLabel2.setText("Número (x)");

        jTextFieldNumeroX.setFont(new java.awt.Font("Barlow Condensed Medium", 0, 36)); // NOI18N
        jTextFieldNumeroX.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jTextFieldNumeroX, javax.swing.GroupLayout.PREFERRED_SIZE, 426, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jTextFieldResultado, javax.swing.GroupLayout.PREFERRED_SIZE, 426, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jTextFieldNumeroX, jTextFieldResultado});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextFieldNumeroX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextFieldResultado, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jTextFieldNumeroX, jTextFieldResultado});

        jButtonCalcular.setFont(new java.awt.Font("Barlow Condensed Medium", 0, 18)); // NOI18N
        jButtonCalcular.setText("Calcular");
        jButtonCalcular.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCalcularActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButtonCalcular)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonCalcular)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

 

No hay comentarios:

Publicar un comentario

Con la tecnología de Blogger.