# Count Unary Numbers in a Range in C++

Given two numbers start and end representing a range. The goal is to find the count of Unary numbers existing between [ start, end ].

We can check if the number is Unary by following steps: If we take a number 13 then 12 + 32 = 10, then 12 + 02 = 1 So the ultimate sum in this way is 1 so 13 is unary.

For Example

## Input

start=1 end=20

## Output

Count of Unary Numbers in a Range are: 5

## Explanation

The numbers are :
1, 7, 10, 12, and 13

## Input

start=50 end=100

## Output

Count of Unary Numbers in a Range are: 7

## Explanation

The numbers are −
59, 63, 67, 74, 75, 78, and 89

Approach used in the below program is as follows

Between 1 and 9 numbers 1 and 7 are unary. For other numbers we will use sums of squares of digits until it gives 1. Continue this process for all numbers in the range. Increment count for all unary numbers found in this manner.

• Take two integers start, end as input.

• Function check_unary(int number) returns true if the passed value is unary else returns false.

• Function Unary_range(int start, int end) takes range variables and returns the count of unary numbers lying in the range.

• Take the initial count as 0. Using for loop, traverse from i=start to end. If check_unary(i) returns true, then increment count.

• Inside check_unary(int number), take temporary variable count.

• If number N is 1, 7, return true. Return false for all other numbers less than 10. ( number/10 == 0 ).

• Then in the while loop calculate the sum of squares of digits.

• Again call check_unary(int number) for such continuous sums until sum becomes 1.

• Return count as result.

## Example

Live Demo

#include <iostream>
using namespace std;
bool check_unary(int number){
int total;
if (number == 1 ){
return true;
}
else if(number == 7){
return true;
}
else if (number / 10 == 0){
return false;
}
while (number!= 0){
int temp = number % 10;
total = total + temp * temp;
number = number / 10;
}
check_unary(total);
}
int Unary_range(int start, int end){
int count = 0;
for (int i = start; i <= end; i++){
if (check_unary(i) == 1){
count++;
}
}
return count;
}
int main(){
int start = 200, end = 400;
cout<<"Count of Unary Numbers in a Range are: "<<Unary_range(start, end);
return 0;
}

## Output

If we run the above code it will generate the following output −

Count of Unary Numbers in a Range are: 31