
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array?
Here we will see how we can find the absolute difference between the sum of all prime numbers and all non-prime numbers of an array. To solve this problem, we have to check whether a number is prime or not. One possible way for primality testing is by checking a number is not divisible by any number between 2 to square root of that number. So this process will take 𝑂(√𝑛) amount of time. Then get the sum and try to find the absolute difference.
Algorithm
diffPrimeNonPrimeSum(arr)
begin sum_p := sum of all prime numbers in arr sum_np := sum of all non-prime numbers in arr return |sum_p – sum_np| end
Example
#include <iostream> #include <cmath> using namespace std; bool isPrime(int n){ for(int i = 2; i<=sqrt(n); i++){ if(n % i == 0){ return false; //not prime } } return true; //prime } int diffPrimeNonPrimeSum(int arr[], int n) { int sum_p = 0, sum_np = 0; for(int i = 0; i<n; i++){ if(isPrime(arr[i])){ sum_p += arr[i]; } else { sum_np += arr[i]; } } return abs(sum_p - sum_np); } main() { int arr[] = { 5, 8, 9, 6, 21, 27, 3, 13}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Difference: " << diffPrimeNonPrimeSum(arr, n); }
Output
Difference: 50
- Related Articles
- Absolute Difference between the Product of Non-Prime numbers and Prime numbers of an Array?
- Print prime numbers with prime sum of digits in an array
- Difference between composite numbers and prime numbers.
- Sum of all prime numbers in an array - JavaScript
- Sum of prime numbers between a range - JavaScript
- Write the difference between composite and prime numbers.
- Sum of the first N Prime numbers
- What are prime numbers and co-prime numbers?
- Sum of all prime numbers in JavaScript
- XOR of all Prime numbers in an Array in C++
- Product of all prime numbers in an Array in C++
- Express an odd number as sum of prime numbers in C++
- Prime numbers after prime P with sum S in C++
- Maximum no. of contiguous Prime Numbers in an array in C++
- Taking the absolute sum of Array of Numbers in JavaScript

Advertisements