I need the Coding of Happy No.
Pls tell me what's wrong with this one.
import java.util.*;
class happy
{
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Entr");
int n=sc.nextInt();
int c=0,d=0,s=0;
while(c!=1)
{
n=s;s=0;c=0;
while(n!=0)
{
d=n%10;
s=s+(d*d);
c++;
n=n/10;
}
}
if(s==1)
{
System.out.println(":)");
}
else
{
System.out.println(":(");
}
}
}
Answers
........
import java.io.*;
class happynumber
{
public
static
void main(
String args)
throws Exception
{
int i,j;
happyno obj=new happyno();
BufferedReader br = new BufferedReade
r(new InputStreamReader(System.in));
System.out.print("enter a number : ");
i=Integer.parseInt(br.readLine());
while((j=obj.happy(i))/10!=0)
// You have to check the sum of all digits until a single digit is achieved
i.e.
sum=1,2,3,..9
{
i =j;
// If sum of digits= 19
it then again goes to 1+9 =10 and again 1+0= '1' a single digit to check if 1 or not
}
if ( j==1) System
.out.println
("It is a happy number ");
else System.out.println
("Not a happy number")
; }
int happy(int n)
{
if(n/10==0) return n*n; else return
(int)Math.pow(n%10,2)+ happy(n/10)
; }
}
Answer:
Explanation:
here is your required program ..go through that u will get your mistake :)
now you will be a happy program...lol
public class HappyNumber
{
//isHappyNumber() will determine whether a number is happy or not
public static int isHappyNumber(int num){
int rem = 0, sum = 0;
//Calculates the sum of squares of digits
while(num > 0){
rem = num%10;
sum = sum + (rem*rem);
num = num/10;
}
return sum;
}
public static void main(String[] args) {
int num = 82;
int result = num;
while(result != 1 && result != 4){
result = isHappyNumber(result);
}
//Happy number always ends with 1
if(result == 1)
System.out.println(num + " is a happy number");
//Unhappy number ends in a cycle of repeating numbers which contains 4
else if(result == 4)
System.out.println(num + " is not a happy number");
}
}
u can change the System.out.println part by your own if you found this complicated its easy....
hope it helps!
plz mark me as brainliest if it helps!