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:
Please Login to comment...