Guest User

Untitled

a guest
May 23rd, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.44 KB | None | 0 0
  1. // Prime.java
  2. //
  3. // input: natural number n
  4. // output: smallest prime number p with p > n
  5. //
  6. // method: apply prime test to n+1, n+2, ... until prime is found,
  7. // prime testing of z is done by testing numbers k = 2 ... with
  8. // k * k <= z if they are factors of z
  9. //
  10.  
  11. import java.awt.*;
  12. import java.applet.Applet;
  13. import java.awt.event.ActionListener;
  14. import java.awt.event.ActionEvent;
  15.  
  16. public class Prime extends Applet {
  17. Label inputPrompt; // declare Label
  18. TextField input, output; // declare textfields for input and output
  19.  
  20. int n, // the input integer read from terminal
  21. z, // candidate for the prime, set to n+1, n+2 etc.
  22. k; // possible divisor of z
  23. boolean divisorFound; // Boolean, indicates that a divisor
  24. // k of z has been found
  25.  
  26. // setup the graphical user interface components
  27. // and initialize labels and text fields
  28. public void init() {
  29. // set layout
  30. setLayout(new FlowLayout( FlowLayout.LEFT));
  31. // set Font
  32. Font myFont = new Font("Times", Font.PLAIN, 18);
  33. setFont(myFont);
  34. setSize(800, 100);
  35.  
  36. inputPrompt = new Label("Geben Sie die Zahl n ein "
  37. + "und druecken Sie Return.");
  38. input = new TextField(10);
  39. input.addActionListener(new ActionListener() {
  40. public void actionPerformed(ActionEvent e) {
  41. // call method for finding next prime
  42.  
  43. String str = "Die naechstgroessere Primzahl nach "
  44. + n + " ist " + findPrime(Integer.parseInt(input.getText())) + '.';
  45.  
  46. // put the sting into the output field
  47. output.setText( str );
  48. }
  49. }); // action will be on input field
  50.  
  51. // output will be text in a field
  52. output = new TextField(60);
  53. output.setEditable(false);
  54. output.setBackground(Color.yellow);
  55.  
  56. add(inputPrompt); // put prompt on applet
  57. add(input); // put input on applet
  58. add(output); // put output on applet
  59. }
  60.  
  61. // function for finding next prime number
  62. public int findPrime(int param) {
  63. // get input number
  64. n = param;
  65. z = n;
  66. do {
  67. z++;
  68. k = 2;
  69. divisorFound = false;
  70. // so far no divisor of z has been found
  71. while ((!divisorFound) && (k*k <= z)) {
  72. // check if k is a divisor of z
  73. if (z % k == 0) {
  74. divisorFound = true;
  75. }
  76. k++;
  77. } //end while
  78. } while (divisorFound);
  79. return z;
  80. // define the output string
  81.  
  82. }
  83. }
Add Comment
Please, Sign In to add comment