Monday, January 02, 2006

Tough one

I could not solve this problem given to me by an engineering student.Argh!
First of all, it is a difficult problem or an easy problem ?

Write a function long count(String N, int M) which returns the number of permutations which are divisible by M.

Example :-
String N = "2753"
and
int M = 5

Returns: 6

The permutations of 2753 that are divisible by 5 are 2375, 2735, 3275, 3725, 7235 and 7325.
and M can have values from 1 to 50.

The only method I can think of is :-

1.Generate all permutations for the string N and store it somewhere like a list or an array.

2.For each element of the list or array, divide by M...IF IT IS DIVISIBLE, increment the counter.

3.Return that counter.

Fine. But how do we do step -1

7 comments:

Dhimant Parekh said...

You don't need to store the numbers anywhere. You just need to count the number of permutations. Now, if you want all permutations which are divisible by 5, you know that the unit's digit has to be 5. Now, the remaining 3 positions have to be filled up by the remaining 3 numbers (which are 2,7 and 3). This means that you are looking at a problem of 3p3 = 3! = 6. You didn't need to actually store those numbers.

sudeep said...

Yeah but thats only for the number "5"...
What would we do for say "7" or "43" ?

But as you said, we may not STORE the nos. ....there might be a way of generating the permuted numbers on the fly and checking divisiblity....

Dhimant Parekh said...

Yes I agree with you. We could check for divisibility and then increment the counter without storing the number.

test123 said...

I think to generate the permutation, you recurse and don't know what later. One way to generate permuations of say 1,2,3 is to
Keep 1.
Place 2 on either side of 1. { (1,2), (2,1) }
Do the same for 3 for each element of the above set. { So (3,1,2),(1,3,2),(1,2,3) will be got from (1,2) by adding 3 }. Similarly for (2,1).

Tejaswi said...

Generating permuations of a reasonably large set of numbers is NP-hard. Additionally divisibility tests for prime numbers like 19, etc are pretty hard. Its a difficult problem, from a computational viewpoint.

Tejaswi said...

http://portal.acm.org/citation.cfm?id=356692

test123 said...

For N numbers, we have N! permutations.
N! > 2**N ( for N >= 4 ).
So worse than exponential.
Between, I couldn't get how you would frame this problem as a decision problem.