Algorithm to find Lucky Numbers

前端 未结 10 980
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-22 21:02

I came across this question.A number is called lucky if the sum of its digits, as well as the sum of the squares of its digits is a prime number. How many numbers between A

10条回答
  •  天命终不由人
    2020-12-22 21:58

    Based on the requirements, you can do it in different ways. If I was doing it, I would calculate the prime numbers using 'Sieve of Eratosthenes' in the required range (A to (9*2)*B.length), cache them (again, depending on your setup, you can use in-memory or disk cache) and use it for the next run.

    I just coded a fast solution (Java), as below (NOTE: Integer overflow is not checked. Just a fast example. Also, my code is not optimized.):

    import java.util.ArrayList;
    import java.util.Arrays;
    
    public class LuckyNumbers {
        public static void main(String[] args) {
            int a = 0, b = 1000;
            LuckyNumbers luckyNums = new LuckyNumbers();
            ArrayList luckyList = luckyNums.findLuckyNums(a, b);
            System.out.println(luckyList);
        }
    
        private ArrayList findLuckyNums(int a, int b) {
            ArrayList luckyList = new ArrayList();
            int size = ("" + b).length();        
            int maxNum = 81 * 4; //9*2*b.length() - 9 is used, coz it's the max digit
            System.out.println("Size : " + size + " MaxNum : " + maxNum);
            boolean[] primeArray = sieve(maxNum);
    
            for(int i=a;i<=b;i++) {
                String num = "" + i;
                int sumDigits = 0;
                int sumSquareDigits = 0;
    
                for(int j=0;j

    And the output was:

    [11, 12, 14, 16, 21, 23, 25, 32, 38, 41, 49, 52, 56, 58, 61, 65, 83, 85, 94, 101, 102, 104, 106, 110, 111, 113, 119, 120, 131, 133, 137, 140, 146, 160, 164, 166, 173, 179, 191, 197, 199, 201, 203, 205, 210, 223, 229, 230, 232, 250, 289, 292, 298, 302, 308, 311, 313, 317, 320, 322, 331, 335, 337, 344, 346, 353, 355, 364, 368, 371, 373, 377, 379, 380, 386, 388, 397, 401, 409, 410, 416, 434, 436, 443, 449, 461, 463, 467, 476, 490, 494, 502, 506, 508, 520, 533, 535, 553, 559, 560, 566, 580, 595, 601, 605, 610, 614, 616, 634, 638, 641, 643, 647, 650, 656, 661, 665, 674, 683, 689, 698, 713, 719, 731, 733, 737, 739, 746, 764, 773, 779, 791, 793, 797, 803, 805, 829, 830, 836, 838, 850, 863, 869, 883, 892, 896, 904, 911, 917, 919, 922, 928, 937, 940, 944, 955, 968, 971, 973, 977, 982, 986, 991]

提交回复
热议问题