Junction Numbers
Last Updated :
13 Jul, 2022
Junction Number is a number N if it can be written as K + SumOfDIgits(k) for at least two K.
101, 103, 105, 107, 109, 111, 113, 115….
Check if a number N is an Junction Number
Given a number N, the task is to check if N is an Junction Number or not. If N is an Junction Number then print “Yes” else print “No”.
Examples:
Input: N = 1106
Output: Yes
Explanation:
1106 = 1093 + (1+0+9+3) = 1102 + (1+1+0+2)
Input: N = 11
Output: No
Approach: Since Junction Number is a number N if it can be written as K + SumOfDIgits(k) for at least two K. So for all numbers from 1 to N in a loop we will check if i + sumOfdigitsof(i) equals to N or not. If equals to N print “Yes” else print “No”.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int sum( int n)
{
int sum = 0;
while (n != 0) {
int r = n % 10;
sum = sum + r;
n = n / 10;
}
return sum;
}
bool isJunction( int n)
{
int count = 0;
for ( int i = 1; i <= n; i++) {
if (i + sum(i) == n)
count++;
}
return count >= 2;
}
int main()
{
int N = 111;
if (isJunction(N))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG{
static int sum( int n)
{
int sum = 0 ;
while (n != 0 )
{
int r = n % 10 ;
sum = sum + r;
n = n / 10 ;
}
return sum;
}
static boolean isJunction( int n)
{
int count = 0 ;
for ( int i = 1 ; i <= n; i++)
{
if (i + sum(i) == n)
count++;
}
return count >= 2 ;
}
public static void main(String[] args)
{
int N = 111 ;
if (isJunction(N))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
import math
def sum1(n):
sum1 = 0
while (n ! = 0 ):
r = n % 10
sum1 = sum1 + r
n = n / / 10
return sum1
def isJunction(n):
count = 0
for i in range ( 1 , n + 1 ):
if (i + sum1(i) = = n):
count = count + 1
return count > = 2
if __name__ = = '__main__' :
n = 111
if (isJunction(n) = = 1 ):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG{
static int sum( int n)
{
int sum = 0;
while (n != 0)
{
int r = n % 10;
sum = sum + r;
n = n / 10;
}
return sum;
}
static bool isJunction( int n)
{
int count = 0;
for ( int i = 1; i <= n; i++)
{
if (i + sum(i) == n)
count++;
}
return count >= 2;
}
public static void Main()
{
int N = 111;
if (isJunction(N))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
function sum( n) {
let sum = 0;
while (n != 0) {
let r = n % 10;
sum = sum + r;
n = parseInt(n / 10);
}
return sum;
}
function isJunction( n) {
let count = 0;
for ( i = 1; i <= n; i++) {
if (i + sum(i) == n)
count++;
}
return count >= 2;
}
let N = 111;
if (isJunction(N))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n)
Space Complexity: O(1)
Reference: http://www.numbersaplenty.com/set/junction_number/
Share your thoughts in the comments
Please Login to comment...