Given a singly linked list containing N nodes, the task is to find the sum and product of all nodes from the list which are prime.
Examples:
Input : List = 15 -> 16 -> 6 -> 7 -> 17
Output : Product = 119, Sum = 24
Prime nodes are 7, 17.
Input : List = 15 -> 3 -> 4 -> 2 -> 9
Output : Product = 6, Sum = 5
Approach: The idea is to traverse the nodes of the singly linked list one by one and check if the current node is prime or not. Find the sum and product of the data of the nodes which are prime.
Below is the implementation of above idea:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
void push(Node** head_ref, int new_data)
{
Node* new_node = (Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
bool isPrime( int n)
{
if (n <= 1)
return false ;
if (n <= 3)
return true ;
if (n % 2 == 0 || n % 3 == 0)
return false ;
for ( int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false ;
return true ;
}
void sumAndProduct(Node* head_ref)
{
int prod = 1;
int sum = 0;
Node* ptr = head_ref;
while (ptr != NULL) {
if (isPrime(ptr->data)) {
prod *= ptr->data;
sum += ptr->data;
}
ptr = ptr->next;
}
cout << "Sum = " << sum << endl;
cout << "Product = " << prod;
}
int main()
{
Node* head = NULL;
push(&head, 17);
push(&head, 7);
push(&head, 6);
push(&head, 16);
push(&head, 15);
sumAndProduct(head);
return 0;
}
|
Java
class GFG
{
static class Node
{
int data;
Node next;
};
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = (head_ref);
(head_ref) = new_node;
return head_ref;
}
static boolean isPrime( int n)
{
if (n <= 1 )
return false ;
if (n <= 3 )
return true ;
if (n % 2 == 0 || n % 3 == 0 )
return false ;
for ( int i = 5 ; i * i <= n; i = i + 6 )
if (n % i == 0 || n % (i + 2 ) == 0 )
return false ;
return true ;
}
static void sumAndProduct(Node head_ref)
{
int prod = 1 ;
int sum = 0 ;
Node ptr = head_ref;
while (ptr != null )
{
if (isPrime(ptr.data))
{
prod *= ptr.data;
sum += ptr.data;
}
ptr = ptr.next;
}
System.out.println( "Sum = " + sum );
System.out.println( "Product = " + prod);
}
public static void main(String args[])
{
Node head = null ;
head=push(head, 17 );
head=push(head, 7 );
head=push(head, 6 );
head=push(head, 16 );
head=push(head, 15 );
sumAndProduct(head);
}
}
|
Python
class Node:
def __init__( self , data):
self .data = data
self . next = next
def push( head_ref, new_data) :
new_node = Node( 0 )
new_node.data = new_data
new_node. next = (head_ref)
(head_ref) = new_node
return head_ref
def isPrime(n) :
if (n < = 1 ) :
return False
if (n < = 3 ) :
return True
if (n % 2 = = 0 or n % 3 = = 0 ) :
return False
i = 5
while ( i * i < = n) :
if (n % i = = 0 or n % (i + 2 ) = = 0 ) :
return False
i = i + 6
return True
def sumAndProduct(head_ref) :
prod = 1
sum = 0
ptr = head_ref
while (ptr ! = None ):
if (isPrime(ptr.data)):
prod * = ptr.data
sum + = ptr.data
ptr = ptr. next
print ( "Sum = " , sum )
print ( "Product = " , prod)
head = None
head = push(head, 17 )
head = push(head, 7 )
head = push(head, 6 )
head = push(head, 16 )
head = push(head, 15 )
sumAndProduct(head)
|
C#
using System;
class GFG
{
public class Node
{
public int data;
public Node next;
};
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = (head_ref);
(head_ref) = new_node;
return head_ref;
}
static bool isPrime( int n)
{
if (n <= 1)
return false ;
if (n <= 3)
return true ;
if (n % 2 == 0 || n % 3 == 0)
return false ;
for ( int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false ;
return true ;
}
static void sumAndProduct(Node head_ref)
{
int prod = 1;
int sum = 0;
Node ptr = head_ref;
while (ptr != null )
{
if (isPrime(ptr.data))
{
prod *= ptr.data;
sum += ptr.data;
}
ptr = ptr.next;
}
Console.WriteLine( "Sum = " + sum);
Console.WriteLine( "Product = " + prod);
}
public static void Main(String []args)
{
Node head = null ;
head = push(head, 17);
head = push(head, 7);
head = push(head, 6);
head = push(head, 16);
head = push(head, 15);
sumAndProduct(head);
}
}
|
Javascript
<script>
class Node {
constructor() {
this .data = 0;
this .next = null ;
}
}
function push(head_ref , new_data) {
var new_node = new Node();
new_node.data = new_data;
new_node.next = (head_ref);
(head_ref) = new_node;
return head_ref;
}
function isPrime(n) {
if (n <= 1)
return false ;
if (n <= 3)
return true ;
if (n % 2 == 0 || n % 3 == 0)
return false ;
for (i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false ;
return true ;
}
function sumAndProduct(head_ref) {
var prod = 1;
var sum = 0;
var ptr = head_ref;
while (ptr != null ) {
if (isPrime(ptr.data)) {
prod *= ptr.data;
sum += ptr.data;
}
ptr = ptr.next;
}
document.write( "Sum = " + sum);
document.write( "<br/>Product = " + prod);
}
var head = null ;
head = push(head, 17);
head = push(head, 7);
head = push(head, 6);
head = push(head, 16);
head = push(head, 15);
sumAndProduct(head);
</script>
|
Output
Sum = 24
Product = 119
complexity Analysis:
- Time Complexity: O(N), where N is the number of nodes in the linked list.
- Auxiliary Space: O(1) because it is using constant space
Approach (Recursive):
We can traverse the linked list recursively and for each node, check if it is prime or not. If it is prime, we add its value to the sum and multiply its value to the product. Then we call the same function recursively for the next node until we reach the end of the list.
- Create a recursive function that takes a pointer to the head of the linked list, a pointer to an integer variable that will hold the sum of prime nodes, and a pointer to an integer variable that will hold the product of prime nodes.
- Check if the head pointer is NULL. If it is, return from the function.
- If the data of the current node is prime, add it to the sum and multiply it to the product.
- Recursively call the function with the next node in the linked list and the updated sum and product variables.
- In the calling function, print the final values of the sum and product variables.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
void push(Node** head_ref, int new_data)
{
Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
bool isPrime( int n)
{
if (n <= 1)
return false ;
if (n <= 3)
return true ;
if (n % 2 == 0 || n % 3 == 0)
return false ;
for ( int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false ;
return true ;
}
void sumAndProductUtil(Node* node, int & prod, int & sum)
{
if (node == NULL)
return ;
if (isPrime(node->data)) {
prod *= node->data;
sum += node->data;
}
sumAndProductUtil(node->next, prod, sum);
}
void sumAndProduct(Node* head)
{
int prod = 1;
int sum = 0;
sumAndProductUtil(head, prod, sum);
cout << "Sum = " << sum << endl;
cout << "Product = " << prod;
}
int main()
{
Node* head = NULL;
push(&head, 17);
push(&head, 7);
push(&head, 6);
push(&head, 16);
push(&head, 15);
sumAndProduct(head);
return 0;
}
|
Java
class Node {
int data;
Node next;
Node( int data)
{
this .data = data;
this .next = null ;
}
}
public class GFG {
static Node push(Node head, int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
return head;
}
static boolean isPrime( int n)
{
if (n <= 1 )
return false ;
if (n <= 3 )
return true ;
if (n % 2 == 0 || n % 3 == 0 )
return false ;
for ( int i = 5 ; i * i <= n; i = i + 6 )
if (n % i == 0 || n % (i + 2 ) == 0 )
return false ;
return true ;
}
static void sumAndProduct(Node node)
{
int prod = 1 ;
int sum = 0 ;
while (node != null ) {
if (isPrime(node.data)) {
prod *= node.data;
sum += node.data;
}
node = node.next;
}
System.out.println( "Sum = " + sum);
System.out.println( "Product = " + prod);
}
public static void main(String[] args)
{
Node head = null ;
head = push(head, 17 );
head = push(head, 7 );
head = push(head, 6 );
head = push(head, 16 );
head = push(head, 15 );
sumAndProduct(head);
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
def push(head_ref, new_data):
new_node = Node(new_data)
new_node. next = head_ref
head_ref = new_node
return head_ref
def isPrime(n):
if n < = 1 :
return False
if n < = 3 :
return True
if n % 2 = = 0 or n % 3 = = 0 :
return False
i = 5
while i * i < = n:
if n % i = = 0 or n % (i + 2 ) = = 0 :
return False
i + = 6
return True
def sumAndProductUtil(node, prod, sum ):
if node is None :
return sum , prod
if isPrime(node.data):
prod * = node.data
sum + = node.data
return sumAndProductUtil(node. next , prod, sum )
def sumAndProduct(head):
prod = 1
sum = 0
sum , prod = sumAndProductUtil(head, prod, sum )
print ( "Sum =" , sum )
print ( "Product =" , prod)
if __name__ = = '__main__' :
head = None
head = push(head, 17 )
head = push(head, 7 )
head = push(head, 6 )
head = push(head, 16 )
head = push(head, 15 )
sumAndProduct(head)
|
C#
using System;
public class Node {
public int data;
public Node next;
public Node( int data)
{
this .data = data;
this .next = null ;
}
}
public class LinkedList {
public Node head;
public void Push( int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
}
public class Program {
public static bool IsPrime( int n)
{
if (n <= 1)
return false ;
if (n <= 3)
return true ;
if (n % 2 == 0 || n % 3 == 0)
return false ;
int i = 5;
while (i * i <= n) {
if (n % i == 0 || n % (i + 2) == 0)
return false ;
i += 6;
}
return true ;
}
public static void
SumAndProductUtil(Node node, ref int prod, ref int sum)
{
if (node == null )
return ;
if (IsPrime(node.data)) {
prod *= node.data;
sum += node.data;
}
SumAndProductUtil(node.next, ref prod, ref sum);
}
public static void SumAndProduct(LinkedList list)
{
int prod = 1;
int sum = 0;
SumAndProductUtil(list.head, ref prod, ref sum);
Console.WriteLine( "Sum = " + sum);
Console.WriteLine( "Product = " + prod);
}
public static void Main( string [] args)
{
LinkedList list = new LinkedList();
list.Push(17);
list.Push(7);
list.Push(6);
list.Push(16);
list.Push(15);
SumAndProduct(list);
}
}
|
Javascript
<script>
class Node {
constructor(data) {
this .data = data;
this .next = null ;
}
}
function push(headRef, newData) {
const newNode = new Node(newData);
newNode.next = headRef;
headRef = newNode;
return headRef;
}
function isPrime(n) {
if (n <= 1) return false ;
if (n <= 3) return true ;
if (n % 2 === 0 || n % 3 === 0) return false ;
for (let i = 5; i * i <= n; i = i + 6) {
if (n % i === 0 || n % (i + 2) === 0) return false ;
}
return true ;
}
function sumAndProductUtil(node, sol) {
if (node === null ) return ;
if (isPrime(node.data)) {
sol.prod *= node.data;
sol.sum += node.data;
}
sumAndProductUtil(node.next, sol);
}
function sumAndProduct(head) {
let sol = {
prod: 1,
sum: 0
};
sumAndProductUtil(head, sol);
document.write( "Sum = " , sol.sum);
document.write( "<br>" );
document.write( "Product = " , sol.prod);
}
let head = null ;
head = push(head, 17);
head = push(head, 7);
head = push(head, 6);
head = push(head, 16);
head = push(head, 15);
sumAndProduct(head);
</script>
|
Output:
Sum = 24
Product = 119
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(p), where p is the number of prime nodes in the linked list.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
30 Nov, 2023
Like Article
Save Article