Check whether the sum of absolute difference of adjacent digits is Prime or not
Last Updated :
27 Nov, 2023
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++
#include<bits/stdc++.h>
using namespace std;
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 ;
}
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 ;
}
int main(){
int num = 142;
string s= "142" ;
if (checkSumPrime(s))
cout<< "Prime\n" ;
else
cout<< "Not Prime\n" ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
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 ;
}
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 ;
}
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" );
}
}
|
Python3
import math as mt
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
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
num = 142
string = str (num)
s = [i for i in string]
if checkSumPrime(s):
print ( "Prime" )
else :
print ( "Not Prime\n" )
|
C#
using System;
class GFG
{
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 ;
}
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 ;
}
public static void Main(String[] args)
{
String str = "142" ;
if (checkSumPrime(str))
Console.WriteLine( "Prime" );
else
Console.WriteLine( "Not Prime" );
}
}
|
Javascript
<script>
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 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 ;
}
let num = 142;
let str = "142" ;
if (checkSumPrime(str))
document.write( "Prime" );
else
document.write( "Not Prime" );
</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
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" );
}
}
}
|
Python3
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)
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
{
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 ;
}
public static bool IsPrimeSumAdjacentDigits( int n)
{
string nString = n.ToString();
MatchCollection matches = Regex.Matches(nString, @"\d" );
int [] digits = new int [nString.Length];
int i = 0;
foreach (Match match in matches)
{
digits[i++] = int .Parse(match.Value);
}
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))
{
Console.WriteLine( "Prime" );
}
else
{
Console.WriteLine( "Not prime" );
}
n = 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);
}
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;
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;
}
bool isPrime( int n, const vector< bool >& sieve) {
return sieve[n];
}
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;
}
bool isSumPrime( int sum, const vector< bool >& sieve) {
return isPrime(sum, sieve);
}
int main() {
int N = 142;
int maxSum = 9 * (to_string(N).length() - 1);
vector< bool > sieve = generateSieve(maxSum);
int sum = calculateSumOfAbsoluteDifferences(N);
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 {
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;
}
static boolean isPrime( int n, List<Boolean> sieve)
{
return sieve.get(n);
}
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;
}
static boolean isSumPrime( int sum, List<Boolean> sieve)
{
return isPrime(sum, sieve);
}
public static void main(String[] args)
{
int N = 142 ;
int maxSum = 9 * (Integer.toString(N).length() - 1 );
List<Boolean> sieve = generateSieve(maxSum);
int sum = calculateSumOfAbsoluteDifferences(N);
boolean isPrimeSum = isSumPrime(sum, sieve);
if (isPrimeSum) {
System.out.println( "Prime" );
}
else {
System.out.println( "Not Prime" );
}
}
}
|
Python3
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
max_sum = 9 * ( len ( str (N)) - 1 )
sieve = generate_sieve(max_sum)
sum = calculate_sum_of_absolute_differences(N)
is_prime_sum = is_sum_prime( sum , sieve)
if is_prime_sum:
print ( "Prime" )
else :
print ( "Not Prime" )
|
C#
using System;
public class Program {
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;
}
public static bool IsPrime( int n, bool [] sieve)
{
return sieve[n];
}
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;
}
public static bool IsSumPrime( int sum, bool [] sieve)
{
return IsPrime(sum, sieve);
}
public static void Main( string [] args)
{
int N = 142;
int maxSum = 9 * ( int )(Math.Log10(N));
bool [] sieve = GenerateSieve(maxSum);
int sum = CalculateSumOfAbsoluteDifferences(N);
bool isPrimeSum = IsSumPrime(sum, sieve);
if (isPrimeSum) {
Console.WriteLine( "Prime" );
}
else {
Console.WriteLine( "Not Prime" );
}
}
}
|
Javascript
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 isPrime(n, sieve) {
return sieve[n];
}
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 isSumPrime(sum, sieve) {
return isPrime(sum, sieve);
}
function main() {
const N = 142;
const maxSum = 9 * (N.toString().length - 1);
const sieve = generateSieve(maxSum);
const sum = calculateSumOfAbsoluteDifferences(N);
const isPrimeSum = isSumPrime(sum, sieve);
if (isPrimeSum) {
console.log( "Prime" );
} else {
console.log( "Not Prime" );
}
}
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...