The 14th Blue Bridge Cup Software Competition Provincial Competition JavaB Group Test Question B: Lucky Number

Question B: Lucky Numbers

[Problem description]
The Harshad number refers to a positive integer that is divisible by the sum of all digits in a fixed base system
. For example, 126 is a Harshad number in decimal, because (126)10 mod (1+2+6) = 0; 126
is also a Harshad number in octal, because (126)10 = (176)8, ( 126)10 mod (1 + 7 + 6) = 0;
at the same time, 126 is also the Harshad number in hexadecimal, because (126)10 = (7e)16, (126)10 mod (7 +
e) ​​= 0 . Xiaolan believes that if an integer is a Harshad number in binary, octal, decimal, and hexadecimal
, then this number is a lucky number, and the decimal representation of the 1st to 10th lucky numbers
is: 1 , 2 , 4, 6, 8, 40, 48, 72, 120, 126 . . .
Now he wants to know what is the 2023th lucky number ? You just need to tell Xiaolan the decimal representation of this integer.
[Answer Submission]
This is a question to fill in the blanks, you only need to calculate the result and submit it. The result of this question is an
integer. When submitting the answer, only fill in this integer. If you fill in the redundant content, you will not get points.

public class LuckyNumber {
    
    
    public static void main(String[] args) {
    
    
        List<Integer> luckyNumbers = new ArrayList<>();
        int count = 0;
        int number = 1;
        while (count < 2023) {
    
    
            if (isHarshadInAllBases(number)) {
    
    
                luckyNumbers.add(number);
                count++;
            }
            number++;
        }
        System.out.println("The 2023rd lucky number is " + luckyNumbers.get(2022));
    }

	//判断某个数是不是幸运数
    private static boolean isHarshadInAllBases(int number) {
    
    
        return isHarshad(number, 10) && isHarshad(number, 2) && isHarshad(number, 8) && isHarshad(number, 16);
    }
    
	//判断某个数是不是哈沙德数
    private static boolean isHarshad(int number, int base) {
    
    
        int a=number;
        int sum = 0;
        while (number > 0) {
    
    
            int digit = number % base;
            sum += digit;
            number /= base;
        }
        return a%sum==0;
    }
}

Guess you like

Origin blog.csdn.net/m0_58121644/article/details/130037888