# Recursive sum of digits of a number is prime or no in C++

C++Server Side ProgrammingProgramming

Given an integer variable number as input. The goal is to calculate the sum of digits of the input number and check if that sum is prime or not. Do this till the obtained number with sum of digits becomes a single digit number. Check if that number is prime or not. If the input number is 123 than the sum of digits will be 1+2+3=6 which is non-prime and also 6 is a single digit number.

## Let us see various input output scenarios for this

Input − number=12341

Output − Recursive sum of digits of a number is PRIME

Explanation

1+2+3+4+1=11

1+1=2

2 is a prime number.

Input − number=1664

Output − Recursive sum of digits of a number is NOT PRIME

Explanation

1+6+6+4=17

1+7=8

8 is a non-prime number.

## Approach used in the below program is as follows

• Declare an integer variable as a number.

• Pass the data to the function as Recursively_Prime(number)

• Inside the function as Recursively_Prime(number)

• Set number to the call to the function as sum(number).

• Check IF number is 3 Or number is 3 OR number is 5 OR number is 7 then print PRIME.

• ELSE, print NOT PRIME.

• Inside the function sum(int number)

• Check IF number is 0 then return 0.

• ELSE, IF number % 9 is 0) then return 9.

• ELSE, number % 9.

• Print the result.

## Example

#include<iostream>
using namespace std;
int sum(int number){
if(number == 0){
return 0;
}
else{
if(number % 9 == 0){
return 9;
}
else{
return number % 9;
}
}
}
void Recursively_Prime(int number){
number = sum(number);
cout<<"Recursive sum of digits of a number is ";
if(number == 2 || number == 3 || number == 5 || number == 7){
cout << "PRIME";
}
else{
cout << "NOT PRIME";
}
}
int main(){
int number = 5555;
Recursively_Prime(number);
}

## Output

If we run the above code it will generate the following Output

Recursive sum of digits of a number is PRIME
Updated on 03-Nov-2021 07:40:46