Computer Science, asked by palakmundra001, 2 months ago

2. WAP to input a number and perform the following task:

i) Find the sum of the digits of the number.

ii) If the sum contains 2 or more than 2 digits then find the sum of the digits of the sum again.

iii) Keep repeating step(ii) unless the sum of the digits is a single digit.

iv) Print “Magic number” , if the sum obtained in single digit is 1. Otherwise print, ‘Not a magic number’.​

Answers

Answered by anindyaadhikari13
2

\texttt{\textsf{\large{\underline{Solution}:}}}

The given c‎ode is written in Java.

import java.util.*;

public class MagicNumber{

   public static void main(String args[]){

       int n,s=0;

       System.out.print("Enter a number: ");

       n=(new Scanner(System.in)).nextInt();

       for(;n>9;n=s,s=0){

           for(;n!=0;s+=n%10,n/=10){}

       }

       if(n==1)

           System.out.println("Number is a magic number.");

       else

       System.out.println("Number is not a magic number: ");

   }

}

A number is said to be a magic number if the recursive sum of its digit is 1. Here, the outer loop iterates till the value of the entered loop is greater than 9. The inner loop calculates the sum of digits and assigns the value of sum in the number. After termination of loop, we have to check whether the number is equal to 1 or not. If true, the number is a magic number else not.

Alternative method: A magic number always leaves 1 as remainder when it is divided by 9. So, we can also solve this problem using this logic.

See the attachment for output.

Attachments:
Answered by Anonymous
1

Answer:

Given a number n, we need to find the sum of its digits such that:

If n < 10    

   digSum(n) = n

Else          

   digSum(n) = Sum(digSum(n))

Examples :

Input : 1234

Output : 1

Explanation : The sum of 1+2+3+4 = 10,  

             digSum(x) == 10

             Hence ans will be 1+0 = 1

Input : 5674

Output : 4

Explanation:

plz mark as brainliest..

Similar questions