Project Euler #58: Spiral primes

  • + 0 comments

    JAva code

    7- 8 cash are not pass

     import java.io.*;
    import java.util.*;
    
    public class Solution {
    
        public static void main(String[] args) {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
              Scanner scanner = new Scanner(System.in);
            int n = scanner.nextInt();
            scanner.close();
    
            int primesCount = 0;
            int i = 3;
            int lastNumber = 1;
    
            while (true) {
                for (int j = 0; j < 4; j++) {
                    lastNumber += i - 1;
                    if (j != 3 && isPrime(lastNumber)) {
                        primesCount++;
                    }
                }
    
                double primesPercentage = (double) primesCount / (1 + 2 * (i - 1)) * 100;
                if (primesPercentage < n) {
                    System.out.println(i);
                    break;
                }
                i += 2;
            }
        }
    
        public static boolean isPrime(int n) {
            if (n <= 1) {
                return false;
            }
            if (n <= 3) {
                return true;
            }
            if (n % 2 == 0 || n % 3 == 0) {
                return false;
            }
    
            int d = n - 1;
            int s = 0;
            while (d % 2 == 0) {
                s++;
                d /= 2;
            }
    
            Random random = new Random();
            for (int i = 0; i < 4; i++) {
                int a = random.nextInt(n - 2) + 2;
                int x = modPow(a, d, n);
                if (x != 1 && x != n - 1) {
                    boolean active = true;
                    for (int r = 0; r < s; r++) {
                        x = modPow(x, 2, n);
                        if (x == n - 1) {
                            active = false;
                            break;
                        }
                    }
                    if (active) {
                        return false;
                    }
                }
            }
            return true;
        }
    
        public static int modPow(int base, int exponent, int mod) {
            int result = 1;
            base %= mod;
            while (exponent > 0) {
                if (exponent % 2 == 1) {
                    result = (int) ((long) result * base % mod);
                }
                base = (int) ((long) base * base % mod);
                exponent /= 2;
            }
            return result;
        }
    }