How Can I Print Out All Prime Numbers in Java?

A prime number is a number with only two factors. These factors include 1 and the number itself. In a Java program, the code must store the number being tested for primality, check the number for primality, then print the number if it is found to be a prime. In the meantime, the program must also keep track of each number that it has tested and how many more numbers it has left to test. The interval of numbers to be checked is defined by the programmer and the program relies primarily on "for" loops and "if" statements to maintain proper flow control of the operation.

Instructions

    • 1

      Create a class to contain your prime number printing program. Example code:

      class PrimeNumbers {

      }

    • 2

      Create the "main" method within your class so that your program can be compiled and run. Also, create some integer type variables within the method for use by the prime number program. Example code:

      public static void main(String args[]) {

      int number1, number2; //Used to keep track of numbers being tested

      int check = 0; //Keeps track of prime numbers

      }

    • 3

      Create a "for" loop to count up to the specified number for which you wish to find primes. The following example code checks numbers between 1 and 100:

      for(number1 = 1;number1<=100;number1++)

      {

      check=0;

      }

    • 4

      Create a second "for" loop nested inside the first "for" loop, to determine a number's primality status, with "if" statements. Example code:

      for(number2=1;number2<number1;number2++)

      {

      if(((number1%number2)==0) & number2!=1) //Determines whether the number is a factor of a second number or is equal to 1

      {

      check=1; //check is set to 1 if the tested number is prime

      }

      }

      if(check==0)

      {

      System.out.println(number1+"\n"); // Prints out each prime number as it is found

      }

      }

    • 5

      Merge all of the code together as one program. The complete example program code:

      class PrimeNumber {

      public static void main(String args[]) {

      int number1, number2; //Used to keep track of numbers being tested

      int check = 0; //Keeps track of prime numbers

      for(number1 = 1;number1<=100;number1++)

      {

      check=0;

      for(number2=1;number2<number1;number2++)

      {

      if(((number1%number2)==0) & number2!=1) //Determines whether the number is a factor of a second number or is equal to 1

      {

      check=1; //check is set to 1 if the tested number is prime

      }

      }

      if(check==0)

      {

      System.out.println(number1+"\n"); //Prints out each prime number as it is found

      }

      }

      }

      }

Related Searches:

References

Comments

Related Ads

Featured