Open In App

Counting pairs with prime bitwise AND in a Singly Linked List

Last Updated : 06 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Singly linked list of integers, the task is to count the number of pairs of nodes whose bitwise AND is a prime number.

Examples:

Input: 4 -> 2 -> 3 -> 1 -> 5 -> 6
Output: 3
Explanation: The only pair with bitwise AND being a prime number is (2, 3), (2, 6), (3, 6).

Input: 10 -> 3 -> 5 -> 7 -> 2 -> 15
Output: 11
Explanation: The pairs with bitwise AND being a prime number are (10, 3), (10, 7), (10, 2), (3, 7), (3, 2), (3, 15), (5, 7), (5, 15), (7, 2), (7, 15), (2, 15).

Approach: This can be solved with the following idea:

To solve this problem, we can iterate through the linked list, and for each node, we can iterate over all nodes after it and check if the bitwise AND of their values is a prime number. If yes, we can increment the count. To check if a number is prime or not, we can write a helper function

Below are the steps to implement the above idea:

  • Define a helper function to check if a given number is prime or not.
  • Define a variable “count” to keep track of the number of pairs with bitwise AND being a prime number.
  • Traverse the linked list using two nested loops :
    • For each node “curr”, traverse all nodes after it using another loop:
      • If the bitwise AND of the values of “curr” and “next” nodes is a prime number, increment the count.
  • Return the count.

Below is the code for the above approach:

C++




// C++ Implementation
#include <bits/stdc++.h>
using namespace std;
 
// Linked list node structure
struct Node {
    int val;
    Node* next;
    Node(int x)
        : val(x), next(NULL)
    {
    }
};
 
// Function to check if a number is prime
bool isPrime(int n)
{
    if (n <= 1)
        return false;
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0)
            return false;
    }
    return true;
}
 
// Function to count the number of pairs
// with bitwise AND being a prime number
int countPairs(Node* head)
{
    int count = 0;
    Node* curr = head;
    while (curr != NULL) {
        Node* next = curr->next;
        while (next != NULL) {
            int and_val = curr->val & next->val;
            if (isPrime(and_val))
                count++;
            next = next->next;
        }
        curr = curr->next;
    }
    return count;
}
 
// Driver code
int main()
{
 
    Node* head1 = new Node(10);
    head1->next = new Node(3);
    head1->next->next = new Node(5);
    head1->next->next->next = new Node(7);
    head1->next->next->next->next = new Node(2);
    head1->next->next->next->next->next = new Node(15);
 
    // Function call
    cout << countPairs(head1) << endl;
    return 0;
}


Java




// Java Implementation
import java.util.*;
 
// Linked list node structure
class Node {
    int val;
    Node next;
 
    Node(int x)
    {
        val = x;
        next = null;
    }
}
 
public class GFG {
    // Function to check if a number is prime
    static boolean isPrime(int n)
    {
        if (n <= 1)
            return false;
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0)
                return false;
        }
        return true;
    }
 
    // Function to count the number of pairs
    // with bitwise AND being a prime number
    static int countPairs(Node head)
    {
        int count = 0;
        Node curr = head;
        while (curr != null) {
            Node next = curr.next;
            while (next != null) {
                int andVal = curr.val & next.val;
                if (isPrime(andVal))
                    count++;
                next = next.next;
            }
            curr = curr.next;
        }
        return count;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        Node head1 = new Node(10);
        head1.next = new Node(3);
        head1.next.next = new Node(5);
        head1.next.next.next = new Node(7);
        head1.next.next.next.next = new Node(2);
        head1.next.next.next.next.next = new Node(15);
 
        // Function call
        System.out.println(countPairs(head1));
    }
}
 
// This code is contributed by Susobhan Akhuli


Python3




# Python Implementation
import math
 
# Linked list node structure
class Node:
    def __init__(self, x):
        self.val = x
        self.next = None
 
# Function to check if a number is prime
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True
 
# Function to count the number of pairs
# with bitwise AND being a prime number
def count_pairs(head):
    count = 0
    curr = head
    while curr:
        next_node = curr.next
        while next_node:
            and_val = curr.val & next_node.val
            if is_prime(and_val):
                count += 1
            next_node = next_node.next
        curr = curr.next
    return count
 
# Driver code
if __name__ == "__main__":
    head1 = Node(10)
    head1.next = Node(3)
    head1.next.next = Node(5)
    head1.next.next.next = Node(7)
    head1.next.next.next.next = Node(2)
    head1.next.next.next.next.next = Node(15)
 
    # Function call
    print(count_pairs(head1))
 
# This code is contributed by Susobhan Akhuli


C#




// C# program for the above approach
using System;
 
// Linked list node structure
public class Node {
    public int val;
    public Node next;
 
    public Node(int x)
    {
        val = x;
        next = null;
    }
}
 
class Program {
    // Function to check if a number is prime
    static bool IsPrime(int n)
    {
        if (n <= 1)
            return false;
 
        for (int i = 2; i <= Math.Sqrt(n); i++) {
            if (n % i == 0)
                return false;
        }
        return true;
    }
 
    // Function to count the number of pairs
    // with bitwise AND being a prime number
    static int CountPairs(Node head)
    {
        int count = 0;
        Node curr = head;
 
        while (curr != null) {
            Node next = curr.next;
 
            while (next != null) {
                int andVal = curr.val & next.val;
 
                if (IsPrime(andVal))
                    count++;
 
                next = next.next;
            }
 
            curr = curr.next;
        }
        return count;
    }
 
    // Driver code
    static void Main()
    {
        Node head1 = new Node(10);
        head1.next = new Node(3);
        head1.next.next = new Node(5);
        head1.next.next.next = new Node(7);
        head1.next.next.next.next = new Node(2);
        head1.next.next.next.next.next = new Node(15);
 
        // Function call
        Console.WriteLine(CountPairs(head1));
    }
}
 
// This code is contributed by Susobhan Akhuli


Javascript




// Linked list node structure
class Node {
    constructor(val) {
        this.val = val;
        this.next = null;
    }
}
 
// Function to check if a number is prime
function isPrime(n) {
    if (n <= 1) return false;
    for (let i = 2; i <= Math.sqrt(n); i++) {
        if (n % i === 0) return false;
    }
    return true;
}
 
// Function to count the number of pairs with bitwise AND being a prime number
function countPairs(head) {
    let count = 0;
    let curr = head;
    while (curr !== null) {
        let next = curr.next;
        while (next !== null) {
            let andVal = curr.val & next.val;
            if (isPrime(andVal)) {
                count++;
            }
            next = next.next;
        }
        curr = curr.next;
    }
    return count;
}
 
// Driver code
const head1 = new Node(10);
head1.next = new Node(3);
head1.next.next = new Node(5);
head1.next.next.next = new Node(7);
head1.next.next.next.next = new Node(2);
head1.next.next.next.next.next = new Node(15);
 
// Function call
console.log(countPairs(head1));


Output

11






Time Complexity: O(n^2 * log(max_val))
Auxiliary Space: O(1) 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads