Check whether the sum of absolute difference of adjacent digits is Prime or not
Last Updated :
11 Jul, 2025
Given a number a N and the task is to check whether the sum of absolute difference of adjacent digit is a prime or not.
Examples:
Input: N = 142
Output: Prime
Sum = |1-4| + |4-2| = 5 i.e. prime.
Input: N = 347
Output: Not prime
Approach: Find the sum of absolute difference of adjacent digits and then check if that sum is prime or not.
Algorithm:
Step 1: Start
Step 2: Create a static function of boolean return type named "prime" which takes an integer value as input and checks if the number is prime or not.
a. in the prime function there are conditions i.e if n==q returns false because 1 is not prime.
b. start a for loop from i=2 to i*i < n and check if (n % i) == 0 then it is not prime if not then prime.
Step 3: Create a static function of boolean return type name it as "checkSumPrime" which takes a string value as input return if the sum of the array is prime or not.
a. initialize an int variable name as "summ" with 0.
b. start a for loop from i=1 to the length of the string
1. The variable summ should be updated to include the absolute difference between the i-th and (i-1)-th characters.
c. check if summ is prime or not return if prime and false if not.
Step 4: End
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach
#include<bits/stdc++.h>
using namespace std;
// Function to check for a prime number
bool Prime(int n){
if( n == 1){
return false;
}
for (int i=2;i*i<=n;i++){
if (n % i == 0)
return false;
}
return true;
}
// Function to find the sum of array
bool checkSumPrime(string st){
int summ = 0;
for (int i=1;i<st.size();i++)
summ+= abs(st[i-1]-st[i]);
if(Prime(summ))
return true;
else
return false;
}
// Driver code
int main(){
int num = 142;
string s= "142";
if (checkSumPrime(s))
cout<<"Prime\n";
else
cout<<"Not Prime\n";
return 0;
}
Java
// Java implementation of the above approach
import java.util.*;
class GFG
{
// Function to check for a prime number
static boolean Prime(int n)
{
if (n == 1)
return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
// Function to find the sum of array
static boolean checkSumPrime(String str)
{
int summ = 0;
for (int i = 1; i < str.length(); i++)
summ += Math.abs(str.charAt(i - 1) -
str.charAt(i));
if (Prime(summ))
return true;
else
return false;
}
// Driver Code
public static void main(String[] args)
{
int num = 142;
String str = "142";
if (checkSumPrime(str))
System.out.println("Prime");
else
System.out.println("Not Prime");
}
}
// This code is contributed by
// sanjeev2552
Python
# Python3 implementation of the above approach
import math as mt
# Function to check for a prime number
def Prime(n):
if n == 1:
return False
for i in range(2, mt.ceil(mt.sqrt(n + 1))):
if n % i == 0:
return False
return True
# Function to find the sum of array
def checkSumPrime(string):
summ = 0
for i in range(1, len(string)):
summ += abs(int(string[i - 1]) -
int(string[i]))
if Prime(summ):
return True
else:
return False
# Driver code
num = 142
string = str(num)
s = [i for i in string]
if checkSumPrime(s):
print("Prime")
else:
print("Not Prime\n")
# This code is contributed by Mohit Kumar
C#
// C# implementation of the above approach
using System;
class GFG
{
// Function to check for a prime number
static bool Prime(int n)
{
if (n == 1)
return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
// Function to find the sum of array
static bool checkSumPrime(String str)
{
int summ = 0;
for (int i = 1; i < str.Length; i++)
summ += Math.Abs(str[i - 1] -
str[i]);
if (Prime(summ))
return true;
else
return false;
}
// Driver Code
public static void Main(String[] args)
{
String str = "142";
if (checkSumPrime(str))
Console.WriteLine("Prime");
else
Console.WriteLine("Not Prime");
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript implementation of the above approach
// Function to check for a prime number
function Prime(n)
{
if (n == 1)
return false;
for(let i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
// Function to find the sum of array
function checkSumPrime(str)
{
let summ = 0;
for(let i = 1; i < str.length; i++)
summ += Math.abs(str[i - 1]-
str[i]);
if (Prime(summ))
return true;
else
return false;
}
// Driver Code
let num = 142;
let str = "142";
if (checkSumPrime(str))
document.write("Prime");
else
document.write("Not Prime");
// This code is contributed by unknown2108
</script>
Time Complexity: O(sum1/2), where the sum is the sum of the digits of the number
Auxiliary Space: O(1)
METHOD 2 :Using re module
APPRAOCH:
The code checks whether the sum of the absolute difference between adjacent digits in a number is a prime number or not.
ALGORITHM:
1.Convert the input number to a list of its digits.
2.Calculate the sum of the absolute difference between adjacent digits in the list.
3.Check if the sum is a prime number using a separate function is_prime.
4.Return True if the sum is prime, False otherwise.
C++
#include <iostream>
#include <cmath>
#include <regex>
using namespace std;
bool is_prime(int n) {
if (n < 2) {
return false;
}
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
bool is_prime_sum_adjacent_digits(int n) {
string numStr = to_string(n);
regex digitsRegex("\\d");
smatch match;
vector<int> digits;
while (regex_search(numStr, match, digitsRegex)) {
digits.push_back(stoi(match.str()));
numStr = match.suffix();
}
int diffSum = 0;
for (int i = 0; i < digits.size() - 1; i++) {
diffSum += abs(digits[i] - digits[i+1]);
}
return is_prime(diffSum);
}
int main() {
int n = 142;
if (is_prime_sum_adjacent_digits(n)) {
cout << "Prime" << endl;
} else {
cout << "Not prime" << endl;
}
n = 347;
if (is_prime_sum_adjacent_digits(n)) {
cout << "Prime" << endl;
} else {
cout << "Not prime" << endl;
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GFG {
public static boolean isPrime(int n)
{
if (n < 2) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static boolean isPrimeSumAdjacentDigits(int n)
{
String nString = Integer.toString(n);
Matcher matcher
= Pattern.compile("\\d").matcher(nString);
int[] digits = new int[nString.length()];
int i = 0;
while (matcher.find()) {
digits[i++] = Integer.parseInt(matcher.group());
}
int diffSum = 0;
for (int j = 0; j < digits.length - 1; j++) {
diffSum += Math.abs(digits[j] - digits[j + 1]);
}
return isPrime(diffSum);
}
public static void main(String[] args)
{
int n = 142;
if (isPrimeSumAdjacentDigits(n)) {
System.out.println("Prime");
}
else {
System.out.println("Not prime");
}
n = 347;
if (isPrimeSumAdjacentDigits(n)) {
System.out.println("Prime");
}
else {
System.out.println("Not prime");
}
}
}
Python
import re
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
def is_prime_sum_adjacent_digits(n):
digits = [int(d) for d in re.findall('\d', str(n))]
diff_sum = sum(abs(digits[i] - digits[i+1]) for i in range(len(digits)-1))
return is_prime(diff_sum)
# Example usage:
n = 142
if is_prime_sum_adjacent_digits(n):
print("Prime")
else:
print("Not prime")
n = 347
if is_prime_sum_adjacent_digits(n):
print("Prime")
else:
print("Not prime")
C#
using System;
using System.Text.RegularExpressions;
class GFG
{
// Function to check if a number is prime
public static bool IsPrime(int n)
{
if (n < 2)
{
return false;
}
for (int i = 2; i <= Math.Sqrt(n); i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
// Function to check if the sum of adjacent digits'
// differences is prime
public static bool IsPrimeSumAdjacentDigits(int n)
{
// Convert the number to a string to extract individual digits
string nString = n.ToString();
// Use regular expression to find all individual digits
MatchCollection matches = Regex.Matches(nString, @"\d");
// Create an array to store the extracted digits
int[] digits = new int[nString.Length];
int i = 0;
// Convert the matched digits back to integers and store
// them in the array
foreach (Match match in matches)
{
digits[i++] = int.Parse(match.Value);
}
// Calculate the sum of absolute differences between
// adjacent digits
int diffSum = 0;
for (int j = 0; j < digits.Length - 1; j++)
{
diffSum += Math.Abs(digits[j] - digits[j + 1]);
}
// Check if the sum of differences is prime using
// the IsPrime function
return IsPrime(diffSum);
}
public static void Main(string[] args)
{
int n = 142;
// Check if the sum of adjacent digits' differences is
// prime for the number 142
if (IsPrimeSumAdjacentDigits(n))
{
Console.WriteLine("Prime");
}
else
{
Console.WriteLine("Not prime");
}
n = 347;
// Check if the sum of adjacent digits' differences is
// prime for the number 347
if (IsPrimeSumAdjacentDigits(n))
{
Console.WriteLine("Prime");
}
else
{
Console.WriteLine("Not prime");
}
}
}
JavaScript
function isPrime(n) {
if (n < 2) {
return false;
}
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
return false;
}
}
return true;
}
function isPrimeSumAdjacentDigits(n) {
const nString = n.toString();
const digits = nString.split('').map(Number);
let diffSum = 0;
for (let j = 0; j < digits.length - 1; j++) {
diffSum += Math.abs(digits[j] - digits[j + 1]);
}
return isPrime(diffSum);
}
// Test cases
let n = 142;
if (isPrimeSumAdjacentDigits(n)) {
console.log("Prime");
} else {
console.log("Not prime");
}
n = 347;
if (isPrimeSumAdjacentDigits(n)) {
console.log("Prime");
} else {
console.log("Not prime");
}
Time complexity is O(log n * sqrt(n)).
Space complexity: The code uses a list to store the digits of the input number, which takes O(log n) space, where n is the input number.
Approach:
1. We include the necessary headers and declare functions to generate a prime sieve, check if a number is prime, calculate the sum of absolute differences of adjacent digits, and check if a sum is prime.
2. In the `main` function, we generate the prime sieve up to the maximum possible sum based on the number of digits in the input number.
3. We calculate the sum of absolute differences of adjacent digits in the input number.
4. Using the prime sieve, we check if the calculated sum is prime.
5. Based on the result, we output whether the sum is prime or not.
C++
#include <iostream>
#include <vector>
using namespace std;
// Function to generate the prime sieve
vector<bool> generateSieve(int limit) {
vector<bool> sieve(limit + 1, true);
sieve[0] = sieve[1] = false;
for (int p = 2; p * p <= limit; ++p) {
if (sieve[p]) {
for (int i = p * p; i <= limit; i += p) {
sieve[i] = false;
}
}
}
return sieve;
}
// Function to check if a number is prime
bool isPrime(int n, const vector<bool>& sieve) {
return sieve[n];
}
// Function to calculate the sum of absolute differences of adjacent digits
int calculateSumOfAbsoluteDifferences(int N) {
int sum = 0;
int prevDigit = N % 10;
N /= 10;
while (N > 0) {
int currDigit = N % 10;
sum += abs(currDigit - prevDigit);
prevDigit = currDigit;
N /= 10;
}
return sum;
}
// Function to check if the sum is prime or not
bool isSumPrime(int sum, const vector<bool>& sieve) {
return isPrime(sum, sieve);
}
int main() {
int N = 142;
// Generate sieve of primes up to the maximum possible sum
int maxSum = 9 * (to_string(N).length() - 1);
vector<bool> sieve = generateSieve(maxSum);
// Calculate the sum of absolute differences
int sum = calculateSumOfAbsoluteDifferences(N);
// Check if the sum is prime or not
bool isPrimeSum = isSumPrime(sum, sieve);
if (isPrimeSum) {
cout << "Prime" << endl;
} else {
cout << "Not Prime" << endl;
}
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
// Function to generate the prime sieve
static List<Boolean> generateSieve(int limit)
{
List<Boolean> sieve = new ArrayList<>(limit + 1);
for (int i = 0; i <= limit; i++) {
sieve.add(true);
}
sieve.set(0, false);
sieve.set(1, false);
for (int p = 2; p * p <= limit; ++p) {
if (sieve.get(p)) {
for (int i = p * p; i <= limit; i += p) {
sieve.set(i, false);
}
}
}
return sieve;
}
// Function to check if a number is prime
static boolean isPrime(int n, List<Boolean> sieve)
{
return sieve.get(n);
}
// Function to calculate the sum of absolute differences
// of adjacent digits
static int calculateSumOfAbsoluteDifferences(int N)
{
int sum = 0;
int prevDigit = N % 10;
N /= 10;
while (N > 0) {
int currDigit = N % 10;
sum += Math.abs(currDigit - prevDigit);
prevDigit = currDigit;
N /= 10;
}
return sum;
}
// Function to check if the sum is prime or not
static boolean isSumPrime(int sum, List<Boolean> sieve)
{
return isPrime(sum, sieve);
}
public static void main(String[] args)
{
int N = 142;
// Generate sieve of primes up to the maximum
// possible sum
int maxSum = 9 * (Integer.toString(N).length() - 1);
List<Boolean> sieve = generateSieve(maxSum);
// Calculate the sum of absolute differences
int sum = calculateSumOfAbsoluteDifferences(N);
// Check if the sum is prime or not
boolean isPrimeSum = isSumPrime(sum, sieve);
if (isPrimeSum) {
System.out.println("Prime");
}
else {
System.out.println("Not Prime");
}
}
}
Python
def generate_sieve(limit):
sieve = [True] * (limit + 1)
sieve[0] = sieve[1] = False
for p in range(2, int(limit ** 0.5) + 1):
if sieve[p]:
for i in range(p * p, limit + 1, p):
sieve[i] = False
return sieve
def is_prime(n, sieve):
return sieve[n]
def calculate_sum_of_absolute_differences(N):
sum = 0
prev_digit = N % 10
N //= 10
while N > 0:
curr_digit = N % 10
sum += abs(curr_digit - prev_digit)
prev_digit = curr_digit
N //= 10
return sum
def is_sum_prime(sum, sieve):
return is_prime(sum, sieve)
if __name__ == "__main__":
N = 142
# Generate sieve of primes up to the maximum possible sum
max_sum = 9 * (len(str(N)) - 1)
sieve = generate_sieve(max_sum)
# Calculate the sum of absolute differences
sum = calculate_sum_of_absolute_differences(N)
# Check if the sum is prime or not
is_prime_sum = is_sum_prime(sum, sieve)
if is_prime_sum:
print("Prime")
else:
print("Not Prime")
#This code is contributed by Rohit Singh
C#
using System;
public class Program {
// Function to generate a sieve of Eratosthenes to find
// prime numbers up to a given limit
public static bool[] GenerateSieve(int limit)
{
bool[] sieve = new bool[limit + 1];
Array.Fill(sieve, true);
sieve[0] = sieve[1] = false;
for (int p = 2; p <= (int)Math.Sqrt(limit); p++) {
if (sieve[p]) {
for (int i = p * p; i <= limit; i += p) {
sieve[i] = false;
}
}
}
return sieve;
}
// Function to check if a number is prime using the
// sieve
public static bool IsPrime(int n, bool[] sieve)
{
return sieve[n];
}
// Function to calculate the sum of absolute differences
// between adjacent digits of a number
public static int
CalculateSumOfAbsoluteDifferences(int N)
{
int sum = 0;
int prevDigit = N % 10;
N /= 10;
while (N > 0) {
int currDigit = N % 10;
sum += Math.Abs(currDigit - prevDigit);
prevDigit = currDigit;
N /= 10;
}
return sum;
}
// Function to check if a number is prime using the
// sieve
public static bool IsSumPrime(int sum, bool[] sieve)
{
return IsPrime(sum, sieve);
}
public static void Main(string[] args)
{
int N = 142;
// Generate a sieve of primes up to the maximum
// possible sum
int maxSum = 9 * (int)(Math.Log10(N));
bool[] sieve = GenerateSieve(maxSum);
// Calculate the sum of absolute differences
int sum = CalculateSumOfAbsoluteDifferences(N);
// Check if the sum is prime or not
bool isPrimeSum = IsSumPrime(sum, sieve);
if (isPrimeSum) {
Console.WriteLine("Prime");
}
else {
Console.WriteLine("Not Prime");
}
}
}
JavaScript
// Function to generate the prime sieve
function generateSieve(limit) {
const sieve = Array(limit + 1).fill(true);
sieve[0] = sieve[1] = false;
for (let p = 2; p * p <= limit; ++p) {
if (sieve[p]) {
for (let i = p * p; i <= limit; i += p) {
sieve[i] = false;
}
}
}
return sieve;
}
// Function to check if a number is prime
function isPrime(n, sieve) {
return sieve[n];
}
// Function to calculate the sum of absolute differences of adjacent digits
function calculateSumOfAbsoluteDifferences(N) {
let sum = 0;
let prevDigit = N % 10;
N = Math.floor(N / 10);
while (N > 0) {
const currDigit = N % 10;
sum += Math.abs(currDigit - prevDigit);
prevDigit = currDigit;
N = Math.floor(N / 10);
}
return sum;
}
// Function to check if the sum is prime or not
function isSumPrime(sum, sieve) {
return isPrime(sum, sieve);
}
// Main function
function main() {
const N = 142;
// Generate sieve of primes up to the maximum possible sum
const maxSum = 9 * (N.toString().length - 1);
const sieve = generateSieve(maxSum);
// Calculate the sum of absolute differences
const sum = calculateSumOfAbsoluteDifferences(N);
// Check if the sum is prime or not
const isPrimeSum = isSumPrime(sum, sieve);
if (isPrimeSum) {
console.log("Prime");
} else {
console.log("Not Prime");
}
}
// Call the main function
main();
Time Complexity:
Generating the prime sieve using the Sieve of Eratosthenes algorithm takes O(N log log N), where N is the maximum possible sum of absolute differences. This is because we iterate up to the square root of N to mark the multiples of prime numbers.
Auxiliary Space:
The space complexity is primarily determined by the size of the prime sieve, which is O(N), where N is the maximum possible sum of absolute differences.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem