Ticker

6/recent/ticker-posts

Neon Number in C++

Neon Number in C++

Neon Number :

A number whose sum of digits of square of the number is equal to the number is called neon number. For example, number 9 is a neon number as its sum of square of its digits is 81 and the sum of the digits is 9. i.e. 9 is a neon number. There are only 3 neon numbers. They are 0, 1, and 9.


Example 1 : 9
      9
=>  9 * 9
=>   81
=>  8+1
=>  9 = Number = 9 , Hence 9 is a Neon number.
Example 2 : 1
      1
=  1 * 1
=   1 = 1 = Number, Hence 1 is an a Neon number.
Example 3 : 7
      7
=  7 * 7
=   49
= 4+9
=13  != 7 , Hence 7 is not a Neon number.


Algorithm to check whether a given number is a Neon Number or not:

Step 1: Accept a number.
Step 2: Calculate the square of a number and store it in a variable (say square).
Step 3: Find the sum of digits of the square of a number and store it in a variable (say sum).
Step 4: If the sum is equal to the accepted number then display "Neon number" else display "Not Neon Number".
Step 5: Stop

Sample Input and Output:

Input 1:    Enter number here --> 1
Output 1: The given number 1 is a Neon number

Input 2:    Enter number here --> 9
Output 2: The given number 9 is a Neon number

Input 3:    Enter number here --> 7
Output 3: The given number 7 is not a Neon number

Question: Write a program in C++ to check whether a given number is a Neon number or not.

Code 1: 


// Program to check whether a given number is a Neon number or not

#include <iostream>

using namespace std;

int main()

{

    int number;

    cout << "Enter number here --> ";

    cin >> number;

    int square = number * number;

    int sum = 0;

    while (square > 0)

    {

        int lastDigit = square % 10;

        sum = sum + lastDigit;

        square = square / 10;
    }

    if (sum == number)

        cout << "The given number " << number << " is a Neon number";

    else

        cout << "The given number " << number << " is not a Neon number";

    return 0;
}


Code 2: 


// Program to check whether a given number is a Neon number or not

#include <iostream>

#include <string> // To use to_string function

using namespace std;

int main()

{

    int number;

    cout << "Enter number here --> ";

    cin >> number;

    int square = number * number;

    string sq = to_string(square);

    int sum = 0;

    for (int i = 0i < sq.length(); i++)

    {

        int currentDigit = sq.at(i) - 48;

        sum = sum + currentDigit;
    }

    if (sum == number)

        cout << "The given number " << number << " is a Neon number";

    else

        cout << "The given number " << number << " is not a Neon number";

    return 0;
}



If you have any doubts/questions related to Program,  feel free to comment below. Subscribe to our blog to get the latest programming updates and inspire me to write more unique programs.

Post a Comment

0 Comments