Java语言实现质数算法

方法一:

public class PrimeNumberExample {
 
      public static boolean isPrime(long n) {
         
          if(n > 2 && (n & 1) == 0)
             return false;
          /* 运用试除法:
           * 1.只有奇数需要被测试
           * 2.测试范围从2与根号{n},反之亦然 */
         for(int i = 3; i * i <= n; i += 2)
             if (n % i == 0) 
                 return false;
         return true;
     }
     
    public static void main(String[] args) {
         int which=0;
         for(int i=2;i<=1000;i++){
             if(isPrime(i)){        
                 which++;
                 if(which % 10 == 0 ){System.out.println();}
                 System.out.print(i+", ");
             }
         }
         System.out.println();
         System.out.print("共有"+which+"个质数.");
     }
 
}

方法一:定义

素数:除了1和它本身以外不再被其他的除数整数。

 for(int i=2; i<1000; i++)
        {
            if(2==i || 3==i){
                System.out.print(i+" ");
                continue;
            }
            int j=2;
            while(j<i){
                if(i%j==0){
                    break;
                }
                j++;
            }
            if(j==i){
                System.out.print(i+" ");
            }
        }

猜你喜欢

转载自blog.csdn.net/album_gyd/article/details/81428824