Soluție HackerRank pentru Twins, subdomeniul Number Theory, în Java 8. Include cerința formatată, exemple, explicația pașilor și cod sursă.

  • Problemă: Twins
  • Domeniu: Number Theory
  • Limbaj: Java 8

Challenge: Twins

Subdomeniu: Number Theory (number-theory)

Scor cont: 30.0 / 30

Submission status: Accepted

Submission score: 1.0

Submission ID: 464727843

Limbaj: java8

Link challenge: https://www.hackerrank.com/challenges/twins/problem

Cerință

Lia is fascinated by anything she considers to be a *twin*. She calls a pairs of positive integers, i and j, twins if:

* They are both prime. A [prime](https://en.wikipedia.org/wiki/Prime_number) number is an integer greater than 1 that has no positive divisors other than 1 and itself.

* Their absolute difference is exactly equal to 2 (i.e., |j - i| = 2).

Given an inclusive interval of integers from n to m, can you help Lia find the number of pairs of twins there are in the interval (i.e., [n, m])? Note that pairs (i, j) and (j, i) are considered to be the same pair.

Input Format

Two space-separated integers describing the respective values of n and m.

Output Format

Print a single integer denoting the number of pairs of twins.

Constraints

* 1 ≤ n ≤ m ≤ 10^9
* m - n ≤ 10^6

Cod sursă

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

public class Solution {
  public static void main(String[] args) {
    final int[] d = { 2, 4, 0 };
    try (final Scanner in = new Scanner(System.in)) {
      final int n = in.nextInt() | 1;
      final int m = in.nextInt();

      int count = n <= 3 && 5 <= m ? 1 : 0;

      final int odd1 = n + d[n % 3];
      final int max = m % 2 == 0 ? m - 3 : m - 2;

      for (int i = odd1; i <= max; i += 6) {
    boolean p1 = BigInteger.valueOf(i).isProbablePrime(30);
    boolean p2 = BigInteger.valueOf(i + 2).isProbablePrime(30);
        if (p1 && p2) {
          count++;
        }
      }
      System.out.print(count);
    }
  }
}
HackerRank Number Theory – Twins