let's Understand what is Happy Number in java:-
Definition:- Any positive integer which is starting from 1 (Greater than 0), and replaces the number by the sum of the squares of its digits, and repeats the all process until the final result becomes 1.For Example check 28 is Happy or Not?
22 + 82 = 4+64 =68
62+82 = 36+64= 100
12+02+02 = 1+0+0= 1
we get 1 that's means this number is a Happy Number.
62+82 = 36+64= 100
12+02+02 = 1+0+0= 1
we get 1 that's means this number is a Happy Number.
NOTE:- if we are not getting 1 that means the number is sad Number.
Here is the list of Happy no under 100:- 1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, and also 100.
Java Code:-
1: import java.util.Scanner;
2: public class HappyNos {
3: static boolean ishappy(int n)
4: {
5: while(n>9){
6: int sum=0;
7: while(n!=0){
8: int r=n%10;
9: sum=sum+r*r;
10: n=n/10;
11: }
12: n=sum;
13: }
14: return n==1||n==7;
15: }
16: static void happyno(int n){
17: System.out.println("Happy nos are");
18: for(int i=1;i<=n;i++){
19: if(ishappy(i)){
20: System.out.print(i+ " ");
21: }
22: }
23: }
24: static int counthappy(int n){
25: int count=0;
26: for(int i=1;i<=n;i++){
27: if(ishappy(i)){
28: count++;
29: }
30: }
31: return count;
32: }
33: static int sumhappy(int n){
34: int sum=0;
35: for(int i=1;i<=n;i++){
36: if(ishappy(i)){
37: sum=sum+i;
38: }
39: }
40: return sum;
41: }
42: public static void main(String[] args) {
43: Scanner sc=new Scanner(System.in);
44: System.out.println("Enter the no");
45: int n=sc.nextInt();
46: boolean b=ishappy(n);
47: if(b)
48: System.out.println("Happy no");
49: else
50: System.out.println("Not happy no");
51: happyno(n);
52: int cnt=counthappy(n);
53: System.out.println("\ntotal happy are "+cnt);
54: int sm=sumhappy(n);
55: System.out.println("total happy are "+sm);
56: }
57: }
Output:-
Enter the no
21
Not happy no
Happy nos are
1 7 10 13 19
total happy are 5
total happy are 50
Explanation of some important lines:-
- first of all, we create a class.
- creating a static method (ishappy).
- in this method, we are using a while loop.
- create a variable.
- after then again using while loop.
- return values after the crack loop.
- create one more static method (happyno).
- used println method for printing happy numbers.
- using for loop.
- using if condition.
- create one more static method (counthappy).
- using for loop.
- one more static method (sumhappy).
- run for loop.
- create the main method.
- import Scanner class.
- use if else condition.
- create a variable and put counthappy method.
- printing the total number of count.
- create one more variable and put the sumhappy method.
- print the total happy number sum.
If you find any error in this program reminds me of the comment. and if you have any questions regarding this program please feel free to ask in the comment below of this post.
Recommended:-
0 Comments