Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Prime.java
- //
- // input: natural number n
- // output: smallest prime number p with p > n
- //
- // method: apply prime test to n+1, n+2, ... until prime is found,
- // prime testing of z is done by testing numbers k = 2 ... with
- // k * k <= z if they are factors of z
- //
- import java.awt.*;
- import java.applet.Applet;
- import java.awt.event.ActionListener;
- import java.awt.event.ActionEvent;
- public class Prime extends Applet {
- Label inputPrompt; // declare Label
- TextField input, output; // declare textfields for input and output
- int n, // the input integer read from terminal
- z, // candidate for the prime, set to n+1, n+2 etc.
- k; // possible divisor of z
- boolean divisorFound; // Boolean, indicates that a divisor
- // k of z has been found
- // setup the graphical user interface components
- // and initialize labels and text fields
- public void init() {
- // set layout
- setLayout(new FlowLayout( FlowLayout.LEFT));
- // set Font
- Font myFont = new Font("Times", Font.PLAIN, 18);
- setFont(myFont);
- setSize(800, 100);
- inputPrompt = new Label("Geben Sie die Zahl n ein "
- + "und druecken Sie Return.");
- input = new TextField(10);
- input.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- // call method for finding next prime
- String str = "Die naechstgroessere Primzahl nach "
- + n + " ist " + findPrime(Integer.parseInt(input.getText())) + '.';
- // put the sting into the output field
- output.setText( str );
- }
- }); // action will be on input field
- // output will be text in a field
- output = new TextField(60);
- output.setEditable(false);
- output.setBackground(Color.yellow);
- add(inputPrompt); // put prompt on applet
- add(input); // put input on applet
- add(output); // put output on applet
- }
- // function for finding next prime number
- public int findPrime(int param) {
- // get input number
- n = param;
- z = n;
- do {
- z++;
- k = 2;
- divisorFound = false;
- // so far no divisor of z has been found
- while ((!divisorFound) && (k*k <= z)) {
- // check if k is a divisor of z
- if (z % k == 0) {
- divisorFound = true;
- }
- k++;
- } //end while
- } while (divisorFound);
- return z;
- // define the output string
- }
- }
Add Comment
Please, Sign In to add comment