1

Possible Duplicate:
Algorithm to find Lucky Numbers

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 and B are lucky? 1 <= A <= B <= 10^18.

I tried this, First I generated all possible primes between 1 and the number that could be resulted by summing the squares (81 *18 = 1458).[Note: I used sieve of Atkin's approach for prime number generation].
And then verifying each number's digit sum and digit square sum is in the list of primes, if so it is lucky otherwise not. But this is very very slow. Is there any better way of solving?

Community
  • 1
  • 1
siva
  • 21
  • 5

2 Answers2

2

Look at my well-explained solution here: Algorithm to find Lucky Numbers (please note - your question was a duplicate of this one).

Community
  • 1
  • 1
OleGG
  • 8,589
  • 1
  • 28
  • 34
0

Just declare a bit array of size 1458, and then set the bit to true if that nubmer is prime, and false otherwise. Then determining if a given number is prime is just a lookup of the corresponding element of the array.

There are lots of explanations of prime number calculation, i.e. sieve of Eratosthenes, sieve of Atkin, etc. Use one of these to initialize the array.

see http://en.wikipedia.org/wiki/Generating_primes

Larry Watanabe
  • 10,126
  • 9
  • 43
  • 46
  • It's right but my main problem is my input.I have to check each and every number(if it was given as 10^18.I have to check from 1 to 10^18 takes more time),so its taking a lot of time.How can we reduce that – siva Feb 12 '12 at 14:49
  • Outside of prime number lookup, the only other things you are doing is I/0, summing and multiplying integers, and array lookup. To speed these things up you basically need to change languages or hardware, but I think that is outside the scope of your solution. – Larry Watanabe Feb 12 '12 at 14:51
  • my problem is not about generating primes,it is about checking a number is lucky or not – siva Feb 12 '12 at 14:52
  • He's already doing that. – Hot Licks Feb 12 '12 at 14:53
  • @Hot Licks, it looks like he is doing a binary search, not an array lookup, in his isPrime algorithm. – Larry Watanabe Feb 12 '12 at 14:55
  • True, but he DID calculate the bool array. He's just not using it right. – Hot Licks Feb 12 '12 at 15:12