Home > Net >  Find amount of happy numbers in a given range
Find amount of happy numbers in a given range

Time:10-08

I need to find all happy numbers in a given range (input)

A happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. 13 is a happy number because 1^2 3^2 = 10 And 1^2 0^2 = 1, thus 13 is a happy number.

So far I have this:

import java.util.HashSet;
import java.util.Set;
import java.util.*;
public class Main {
  public static void main(String[] args) {
  
    Scanner scan = new Scanner(System.in);
    String wrd = scan.nextLine().trim();
    String wrd2 = scan.nextLine().trim();

    int nieuwnummer = Integer.parseInt(wrd);
    int nieuwnummer2 = Integer.parseInt(wrd2);

    // int count = 0
    
    Set<Integer> numbers = new HashSet<Integer>();
        for (int i = nieuwnummer; i <= nieuwnummer2; i  ) { while(nieuwnummer>0) {
                nieuwnummer2  = (nieuwnummer % 10)*(nieuwnummer % 10); 
                nieuwnummer /=10; };
            }
      
            nieuwnummer = nieuwnummer2;
        }
      //System.out.println(count)
    
  }

I think the range isn't working yet and I need a way to actually count the happy number. Please help :)

CodePudding user response:

Idk if I understand you correctly but

You have while(nieuwnummer>0) which is some number on start but after first loop it is changing to 0 [ eg. if range is from 1 to 16] so it will go one time and then skip.

for that kind of problem I would use smth like here : https://www.geeksforgeeks.org/lucky-numbers/

and itterate through the loop

CodePudding user response:

Here is some working example.

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String st1 = scan.nextLine().trim();
        String st2 = scan.nextLine().trim();

        int min = Integer.parseInt(st1);
        int max = Integer.parseInt(st2);

        Set<Integer> happyNumbers = getHappyNumbers(min, max);
        System.out.println(happyNumbers.size());

    }

    public static Set<Integer> getHappyNumbers(int min, int max) {
        Set<Integer> out = new HashSet<>();
        for (int i = min; i < max; i  ) {
            if (isHappy(i)) {
                out.add(i);
            }
        }
        return out;
    }

    private static boolean isHappy(int i) {
        int sum = 0;
        while (i != 0) {
            sum  = Math.pow((i % 10), 2);
            i /= 10;
        }
        if (sum == 1) return true;
        else if (sum >= 10) {return isHappy(sum);}
        else return false;
    }
}
  •  Tags:  
  • java
  • Related