From 0484f5d819effe326a8fbf99c8622d8d23b76beb Mon Sep 17 00:00:00 2001 From: Disha Thakurata <146114938+dishathakurata@users.noreply.github.com> Date: Sun, 16 Jun 2024 21:13:57 +0530 Subject: [PATCH] Create Prime pair with target sum --- Prime pair with target sum | 76 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Prime pair with target sum diff --git a/Prime pair with target sum b/Prime pair with target sum new file mode 100644 index 0000000..e0ec5eb --- /dev/null +++ b/Prime pair with target sum @@ -0,0 +1,76 @@ +//Prime pair with target sum + +import java.io.*; +import java.util.*; +import java.util.ArrayList; + +class IntArray { + public static int[] input(BufferedReader br, int n) throws IOException { + String[] s = br.readLine().trim().split(" "); + int[] a = new int[n]; + + for(int i = 0; i < n; i++) + a[i] = Integer.parseInt(s[i]); + + return a; + } + + public static void print(int[] a) { + for(int e : a) + System.out.print(e + " "); + System.out.println(); + } + + public static void print(ArrayList a) { + for(int e : a) + System.out.print(e + " "); + System.out.println(); + } +} + +class GFG { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int t = Integer.parseInt(br.readLine()); + + while(t-- > 0) { + int n = Integer.parseInt(br.readLine()); + Solution obj = new Solution(); + ArrayList res = obj.getPrimes(n); + IntArray.print(res); + } + } +} + +class Solution { + + public static ArrayList getPrimes(int n) { + boolean prime[] = new boolean[n + 1]; + Arrays.fill(prime, true); + prime[0] = false; + prime[1] = false; + ArrayList ans = new ArrayList(); + + for(int i = 2; i * i <= n; i++) { + if(prime[i]) { + for(int j = i * i; j <= n; j += i) { + prime[j] = false; + } + } + } + + for(int i = 2; i <= n; i++) { + if(prime[i] && prime[n - i]) { + ans.add(i); + ans.add(n - i); + + return ans; + } + } + + ans.add(-1); + ans.add(-1); + + return ans; + } +}