Search code examples
algorithmprime-factoringnumber-theory

How many numbers are there upto N which have digits 2,3,5 and divisible by 2,3,5?


I have a set of digits {d1,d2,d3......dn} where , 1<=di<=9. 1<=n<=9

Now I wish to find out how many numbers are there <=N which have all these digits in them , in any order , and all those numbers are also divisible by these digits .

The way I think , is just to iterate from first number with length n to N and check , but is there more efficient solution ?

Example :

D = {2,3,5} and N = 10^10

How many numbers are there which have all these digits in them and are also multiple of 2,3 and 5.


Solution

  • I'm not sure from your question if you want numbers that are only divisible by 2, 3 and 5, or if you will accept numbers divisible by some other number as long as 2, 3 and 5 are among the divisors. Assuming the first alternative:

    First, compute the hamming numbers (numbers divisible by 2, 3 and 5); there are only a few thousand of them under 10^10, and they are easy to compute. Second, examine each one to determine if it uses digits other than 2, 3 or 5.

    The hamming numbers can be computed by induction. Start with 1, which is a hamming number. Then, if x is a hamming number, so are 2 x, 3 x and 5 x.

    If you need help reducing this to code, ask.

    EDIT: Based on the comment below, you want the second alternative ("have to check all multiples of 2"). Consider then the case for 2, 3 and 5. First generate all 1-digit numbers containing 2, 3 or 5, which is trivial. Then generate all 2-digit numbers containing 2, 3 or 5: 22, 23, 25, 32, 33, 35, 52, 53, 55. And so on for each n-digit number up to your limit. Finally, test each for divisibility; for the list above, 23 and 53 would be excluded as not being divisible by 2, 3 or 5.

    In either case, the trick is to generate a small set of numbers that meets one of the criteria, then check the other criteria.