|
| 1 | +import java.io.*; |
| 2 | +import java.math.*; |
| 3 | +import java.security.*; |
| 4 | +import java.text.*; |
| 5 | +import java.util.*; |
| 6 | +import java.util.concurrent.*; |
| 7 | +import java.util.regex.*; |
| 8 | + |
| 9 | +public class Solution { |
| 10 | + |
| 11 | + // Complete the redJohn function below. |
| 12 | + static int redJohn(int n) { |
| 13 | + |
| 14 | + int m = numWays(n, new HashMap<>()); |
| 15 | + return primes(m); |
| 16 | + |
| 17 | + } |
| 18 | + |
| 19 | + static int numWays(int n, Map<Integer, Integer> memo) { |
| 20 | + if (memo.containsKey(n)) return memo.get(n); |
| 21 | + if (n == 4) return 2; |
| 22 | + if (n < 4) return 1; |
| 23 | + |
| 24 | + int result = numWays(n - 1, memo) + numWays(n - 4, memo); |
| 25 | + |
| 26 | + memo.put(n, result); |
| 27 | + |
| 28 | + return result; |
| 29 | + } |
| 30 | + |
| 31 | + static int primes(int m) { |
| 32 | + int num = 0; |
| 33 | + |
| 34 | + for(int i = 0; i <= m; i++) { |
| 35 | + if (isPrime(i)) num++; |
| 36 | + } |
| 37 | + |
| 38 | + return num; |
| 39 | + } |
| 40 | + |
| 41 | + static boolean isPrime(int n) { |
| 42 | + |
| 43 | + if (n < 2) return false; |
| 44 | + |
| 45 | + |
| 46 | + for(int i = 2; i <= Math.sqrt(n); i++) { |
| 47 | + if (n % i == 0) return false; |
| 48 | + } |
| 49 | + |
| 50 | + return true; |
| 51 | + } |
| 52 | + |
| 53 | + private static final Scanner scanner = new Scanner(System.in); |
| 54 | + |
| 55 | + public static void main(String[] args) throws IOException { |
| 56 | + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); |
| 57 | + |
| 58 | + int t = scanner.nextInt(); |
| 59 | + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); |
| 60 | + |
| 61 | + for (int tItr = 0; tItr < t; tItr++) { |
| 62 | + int n = scanner.nextInt(); |
| 63 | + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); |
| 64 | + |
| 65 | + int result = redJohn(n); |
| 66 | + |
| 67 | + bufferedWriter.write(String.valueOf(result)); |
| 68 | + bufferedWriter.newLine(); |
| 69 | + } |
| 70 | + |
| 71 | + bufferedWriter.close(); |
| 72 | + |
| 73 | + scanner.close(); |
| 74 | + } |
| 75 | +} |
0 commit comments