显示素数

import java.util.*;
import javax.swing.*;  
  class Main {
    public static void main(String[] args){
      final int NUMBER_OF_PRIMES = 50;//Number of primes to display
      final int NUMBER_OF_PRIMES_PER_LINE = 10;//Display 10 per line
      int count = 0;//Count the number of prime numbers
      int number = 2;//A number to be tested for primeness
      
      System.out.println("The first 50 prime numbers are \n");
      
      //Repeatdly find prime numbers
      while(count < NUMBER_OF_PRIMES){
        //Assume the number is prime
        boolean isPrime = true;//Is the current number prime?

        //Test whethehr number is prime
        for(int divisor = 2;divisor <= number / 2; divisor++){
          if(number % divisor == 0){//If ture,the number is not prime
            isPrime = false;//Set isPrime to false
            break;//Exit the for loop
          }
        }

        //Print thte prime number and increase the count
        if(isPrime){
          count++;
          if(count % NUMBER_OF_PRIMES_PER_LINE == 0){
            System.out.printf("%-4d", number);
            System.out.print("\n");
          }else{
            System.out.printf("%-4d", number);
          }
       }
        number++;
      }
   }
  }

打印2-1000之间的素数,每行8个

import java.util.*;
import javax.swing.*;  
  class Main {
    public static void main(String[] args){
      int count = 0;
      for(int i = 2; i <= 1000; i++){
        boolean isPrime = true;//Is the current number prime?

        //Test whethehr number is prime
        for(int divisor = 2;divisor <= i / 2; divisor++){
          if(i % divisor == 0){//If ture,the number is not prime
            isPrime = false;//Set isPrime to false
            break;//Exit the for loop
          }
        }
        
        //Print thte prime number and increase the count
        if(isPrime){
          count++;
          if(count % 8 == 0){
            System.out.printf("%-4d", i);
            System.out.print("\n");
          }else{
            System.out.printf("%-4d", i);
          }
       }        
      }
    }
  }
posted @ 2022-05-20 11:56  Scenery_Shelley  阅读(27)  评论(0编辑  收藏  举报