Skip to content

Commit

Permalink
Create Prime pair with target sum
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored Jun 16, 2024
1 parent c23e3e1 commit 0484f5d
Showing 1 changed file with 76 additions and 0 deletions.
76 changes: 76 additions & 0 deletions Prime pair with target sum
Original file line number Diff line number Diff line change
@@ -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<Integer> 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<Integer> res = obj.getPrimes(n);
IntArray.print(res);
}
}
}

class Solution {

public static ArrayList<Integer> getPrimes(int n) {
boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
prime[0] = false;
prime[1] = false;
ArrayList<Integer> ans = new ArrayList<Integer>();

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;
}
}

0 comments on commit 0484f5d

Please sign in to comment.