Self Numbers
Last Updated :
01 Aug, 2021
A Number N is said to be Self Number if it can not be written as M + sum of digits of M for any M.
The first few Self numbers are:
1, 3, 5, 7, 9, 20, 31, 42…………….
Check if N is a Self number
Given an integer N, the task is to find if this number is Self number or not.
Examples:
Input: N = 3
Output: Yes
Explanation:
1 + sumofDigits(1) = 2
2 + sumofDigits(2) = 4
3 + sumofDigits(3) = 6
Hence 3 can not be written as
m + sum of digits of m for any m.
Input: N = 4
Output: No
2 + sumodDigits(2) = 4
Approach: The idea is to iterate from 1 to N and for each number check that sum of its value and sum of its digit is equal to N or not. If yes then the number is not a self number. Otherwise, the number is a self number.
For Example:
if N = 3
// Check for every number
// from 1 to N
1 + sumofDigits(1) = 1
2 + sumofDigits(2) = 4
3 + sumofDigits(3) = 6
Hence 3 can not be written as
M + sum of digits of M for any M.
Below is the implementation of the above approach:
Example :
C++
#include <bits/stdc++.h>
using namespace std;
int getSum( int n)
{
int sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
bool isSelfNum( int n)
{
for ( int m = 1; m <= n; m++) {
if (m + getSum(m) == n)
return false ;
}
return true ;
}
int main()
{
int n = 20;
if (isSelfNum(n)) {
cout << "Yes" ;
}
else {
cout << "No" ;
}
return 0;
}
|
Java
class GFG{
static int getSum( int n)
{
int sum = 0 ;
while (n != 0 )
{
sum = sum + n % 10 ;
n = n / 10 ;
}
return sum;
}
static boolean isSelfNum( int n)
{
for ( int m = 1 ; m <= n; m++)
{
if (m + getSum(m) == n)
return false ;
}
return true ;
}
public static void main(String[] args)
{
int n = 20 ;
if (isSelfNum(n))
{
System.out.println( "Yes" );
}
else
{
System.out.println( "No" );
}
}
}
|
Python3
def getSum(n):
sum1 = 0 ;
while (n ! = 0 ):
sum1 = sum1 + n % 10 ;
n = n / / 10 ;
return sum1;
def isSelfNum(n):
for m in range ( 1 , n + 1 ):
if (m + getSum(m) = = n):
return False ;
return True ;
n = 20 ;
if (isSelfNum(n)):
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG{
static int getSum( int n)
{
int sum = 0;
while (n != 0)
{
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
static bool isSelfNum( int n)
{
for ( int m = 1; m <= n; m++)
{
if (m + getSum(m) == n)
return false ;
}
return true ;
}
public static void Main()
{
int n = 20;
if (isSelfNum(n))
{
Console.Write( "Yes" );
}
else
{
Console.Write( "No" );
}
}
}
|
Javascript
<script>
function getSum( n)
{
let sum = 0;
while (n != 0)
{
sum = sum + n % 10;
n = parseInt(n / 10);
}
return sum;
}
function isSelfNum( n) {
for ( let m = 1; m <= n; m++) {
if (m + getSum(m) == n)
return false ;
}
return true ;
}
let n = 20;
if (isSelfNum(n)) {
document.write( "Yes" );
} else {
document.write( "No" );
}
</script>
|
Time Complexity: O(log10N)
Auxiliary Space: O(1)
References: https://en.wikipedia.org/wiki/Self_number
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...