Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmSum of array elements which are prime factors of a given number

Sum of array elements which are prime factors of a given number

Given an array arr[] of size N and a positive integer K, the task is to find the sum of all array elements which are prime factors of K.

Examples:

Input: arr[] = {1, 2, 3, 5, 6, 7, 15}, K = 35
Output: 12
Explanation: From the given array, 5 and 7 are prime factors of 35. Therefore, required sum = 5 + 7 = 12.

Input: arr[] = {1, 3, 5, 7}, K = 42
Output: 10
Explanation: From the given array, 3 and 7 are prime factors of 42. Therefore, required sum = 3 + 7 = 10.

Approach: The idea is to traverse the array and for each array element, check if it is a prime factor of K or not. Add those elements to the sum, for which the condition satisfies. Follow the steps below to solve the problem:

  • Initialize a variable, say sum, to store the required sum.
  • Traverse the given array, and for each array element, perform the following operations:
  • After complete traversal of the array, print the value of the sum as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if a
// number is prime or not
bool isPrime(int n)
{
    // Corner cases
    if (n <= 1)
        return false;
    if (n <= 3)
        return true;
 
    // Check if n is a
    // multiple of 2 or 3
    if (n % 2 == 0 || n % 3 == 0)
        return false;
 
    // Above condition allows to check only
    // for every 6th number, starting from 5
    for (int i = 5; i * i <= n; i = i + 6)
 
        // If n is a multiple of i and i + 2
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
 
    return true;
}
 
// Function to find the sum of array
// elements which are prime factors of K
void primeFactorSum(int arr[], int n, int k)
{
 
    // Stores the required sum
    int sum = 0;
 
    // Traverse the given array
    for (int i = 0; i < n; i++) {
 
        // If current element is a prime
        // factor of k, add it to the sum
        if (k % arr[i] == 0 && isPrime(arr[i])) {
            sum = sum + arr[i];
        }
    }
 
    // Print the result
    cout << sum;
}
 
// Driver Code
int main()
{
 
    // Given arr[]
    int arr[] = { 1, 2, 3, 5, 6, 7, 15 };
 
    // Store the size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    int K = 35;
 
    primeFactorSum(arr, N, K);
 
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG
{
 
    // Function to check if a
    // number is prime or not
    static boolean isPrime(int n)
    {
       
        // Corner cases
        if (n <= 1)
            return false;
        if (n <= 3)
            return true;
 
        // Check if n is a
        // multiple of 2 or 3
        if (n % 2 == 0 || n % 3 == 0)
            return false;
 
        // Above condition allows to check only
        // for every 6th number, starting from 5
        for (int i = 5; i * i <= n; i = i + 6)
 
            // If n is a multiple of i and i + 2
            if (n % i == 0 || n % (i + 2) == 0)
                return false;
 
        return true;
    }
 
    // Function to find the sum of array
    // elements which are prime factors of K
    static void primeFactorSum(int arr[], int n, int k)
    {
 
        // Stores the required sum
        int sum = 0;
 
        // Traverse the given array
        for (int i = 0; i < n; i++) {
 
            // If current element is a prime
            // factor of k, add it to the sum
            if (k % arr[i] == 0 && isPrime(arr[i]))
            {
                sum = sum + arr[i];
            }
        }
 
        // Print the result
        System.out.println(sum);
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Given arr[]
        int arr[] = { 1, 2, 3, 5, 6, 7, 15 };
 
        // Store the size of the array
        int N = arr.length;
        int K = 35;
        primeFactorSum(arr, N, K);
    }
}
 
// This code is contributed by Kingash.


Python3




# Python3 program for the above approach
 
# Function to check if a
# number is prime or not
def isPrime(n):
     
    # Corner cases
    if (n <= 1):
        return False
    if (n <= 3):
        return True
 
    # Check if n is a
    # multiple of 2 or 3
    if (n % 2 == 0 or n % 3 == 0):
        return False
 
    # Above condition allows to check only
    # for every 6th number, starting from 5
    i = 5
     
    while (i * i <= n ):
 
        # If n is a multiple of i and i + 2
        if (n % i == 0 or n % (i + 2) == 0):
            return False
         
        i = i + 6
         
    return True
 
# Function to find the sum of array
# elements which are prime factors of K
def primeFactorSum(arr, n, k):
 
    # Stores the required sum
    sum = 0
 
    # Traverse the given array
    for i in range(n):
 
        # If current element is a prime
        # factor of k, add it to the sum
        if (k % arr[i] == 0 and isPrime(arr[i])):
            sum = sum + arr[i]
         
    # Print the result
    print(sum)
 
# Driver Code
 
# Given arr[]
arr = [ 1, 2, 3, 5, 6, 7, 15 ]
 
# Store the size of the array
N = len(arr)
 
K = 35
 
primeFactorSum(arr, N, K)
 
# This code is contributed by code_hunt


C#




// C# program for the above approach
using System;
 
class GFG
{
 
    // Function to check if a
    // number is prime or not
    static bool isPrime(int n)
    {
       
        // Corner cases
        if (n <= 1)
            return false;
        if (n <= 3)
            return true;
 
        // Check if n is a
        // multiple of 2 or 3
        if (n % 2 == 0 || n % 3 == 0)
            return false;
 
        // Above condition allows to check only
        // for every 6th number, starting from 5
        for (int i = 5; i * i <= n; i = i + 6)
 
            // If n is a multiple of i and i + 2
            if (n % i == 0 || n % (i + 2) == 0)
                return false;
 
        return true;
    }
 
    // Function to find the sum of array
    // elements which are prime factors of K
    static void primeFactorSum(int []arr, int n, int k)
    {
 
        // Stores the required sum
        int sum = 0;
 
        // Traverse the given array
        for (int i = 0; i < n; i++) {
 
            // If current element is a prime
            // factor of k, add it to the sum
            if (k % arr[i] == 0 && isPrime(arr[i]))
            {
                sum = sum + arr[i];
            }
        }
 
        // Print the result
        Console.Write(sum);
    }
 
    // Driver code
    public static void Main(string[] args)
    {
 
        // Given arr[]
        int []arr = { 1, 2, 3, 5, 6, 7, 15 };
 
        // Store the size of the array
        int N = arr.Length;
        int K = 35;
        primeFactorSum(arr, N, K);
    }
}
 
// This code is contributed by ukasp.


Javascript




<script>
 
// Javascript program for the above approach
 
// Function to check if a
// number is prime or not
function isPrime(n)
{
    // Corner cases
    if (n <= 1)
        return false;
    if (n <= 3)
        return true;
 
    // Check if n is a
    // multiple of 2 or 3
    if (n % 2 == 0 || n % 3 == 0)
        return false;
     
    var i;
    // Above condition allows to check only
    // for every 6th number, starting from 5
    for (i = 5; i * i <= n; i = i + 6)
 
        // If n is a multiple of i and i + 2
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
 
    return true;
}
 
// Function to find the sum of array
// elements which are prime factors of K
function primeFactorSum(arr, n, k)
{
 
    // Stores the required sum
    var sum = 0;
    var i;
    // Traverse the given array
    for (i = 0; i < n; i++) {
 
        // If current element is a prime
        // factor of k, add it to the sum
        if (k % arr[i] == 0 && isPrime(arr[i])) {
            sum = sum + arr[i];
        }
    }
 
    // Print the result
    document.write(sum);
}
 
// Driver Code
    // Given arr[]
    var arr = [1, 2, 3, 5, 6, 7, 15]
 
    // Store the size of the array
    var N = arr.length;
 
    var K = 35;
 
    primeFactorSum(arr, N, K);
 
</script>


Output: 

12

 

Time Complexity: O(N*?X), where X is the largest element in the array
Auxiliary Space: O(1)

 

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 neveropen!

Calisto Chipfumbu
Calisto Chipfumbuhttp://cchipfumbu@gmail.com
I have 5 years' worth of experience in the IT industry, primarily focused on Linux and Database administration. In those years, apart from learning significant technical knowledge, I also became comfortable working in a professional team and adapting to my environment, as I switched through 3 roles in that time.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments