2018年7月27日 星期五

Java 質數又來囉

題目: 質數又來囉

使用這篇文章判斷質數去修改

import java.util.Scanner;
import java.math.BigInteger;

public class Prime {
  
    public static boolean MillerRabin(BigInteger x, int d, int time, BigInteger n){
        BigInteger nDivOne = n.subtract( BigInteger.ONE );
        BigInteger TWO = BigInteger.valueOf(2);
        x = x.modPow(BigInteger.valueOf(d), n);
  
        if( !x.equals( BigInteger.ONE ) && !x.equals( nDivOne ) ){
   
            while( --time > 0 ){
                x = x.modPow(TWO, n);
                if( x.equals( nDivOne ) ){ return true; }
            }
            return false;
        }
        return true;
    }
 
    public static int d,s;
    public static boolean isPrime(int n){  
        d = n - 1;
        s = 0;
        while( d % 2 == 0 ){
            d /= 2;
            s++;
        }
  
        return MillerRabin(BigInteger.valueOf(2), d, s, BigInteger.valueOf(n)) &&
               MillerRabin(BigInteger.valueOf(7), d, s, BigInteger.valueOf(n)) &&
               MillerRabin(BigInteger.valueOf(61), d, s, BigInteger.valueOf(n));
    }

    public static Scanner sc = new Scanner(System.in);
    public static int a,b,total;
 
    public static void main(String[] args){
          
        while(sc.hasNext()){
            a = sc.nextInt();
            b = sc.nextInt();
            total = 0;
    
            do{
                if(a % 2 ==0 && a > 2 || a == 1){
                    a++;
                    continue;
                }
                switch( a ){
                    case 2: case 5: case 7: case 61:
                        total++;
                        a++;
                        break;
                    default:
                        switch( a % 10 ){
                            case 1: case 3: case 5: case 7: case 9:
                                total += isPrime(a) ? 1 : 0;
                                a+=2;
                                break;
                        }
                        break;
                }
            }while( a <= b );
   
            System.out.println(total);
        }
    }
}

沒有留言:

張貼留言