Money Matters Solution: A recursive approach


Problem Statement:
The Government of Byteland has decide to issue new currency notes with special protection features to commemorate a great mathematician. 

It has decided to issue notes summing up to N such that all the sums from 1 to N should be possible to be made by selecting some of the notes. Also this has to be done in way such that if any note from 1 to N can be made in more than one way by combining other selected notes then that set of notes is not valid.

For example, with N = 7,

The valid sets are:
{1,1,1,1,1,1,1}
{1,1,1,4}
{1,2,2,2}
{1,2,4}

Invalid sets are:
{1,1,1,2,2} beacuse the sum adds up to 7 but 2 can be made by {1,1} and {2}, 3 can be made by {1,1,1} and {1,2}, 4 can be made by {1,1,2} and {2,2} and similarly 5, 6 and 7 can also be made in multiple ways using the same set.
{1,1,3,6} beacuse all from 1 to 7 can be uniquely made but the sum is not 7 (its 11).

Before implementing this idea of issuing these new set of notes, the Government wants to know how many possible valid sets are there for a given N. Your program should help the Government to find this out.

Input

First line will contain the number of test cases T (1<=T<=6666).
Each test case will have one line containing an integer N (<= 2^31-1).

Output

For each value of N output the total number of valid sets on a separate line.

Example

Input:
3
7
111212121
1000

Output:
4
75
13

Solution:

//Solved by Sanjay Verma
  1. #include<stdio.h>
  2. #define memSize 3333
  3. int noofsol(int);
  4. int count[memSize];
  5. main()
  6. {
  7. int t,x;
  8. count[0]=0;
  9. count[1]=1;
  10. count[2]=1;
  11. count[3]=2;
  12. count[4]=1;
  13. scanf("%d",&t);
  14. while(t--)
  15. {
  16. scanf("%d",&x);
  17. printf("%d\n",noofsol(x));
  18. }
  19. return 0;
  20. }
  21. int noofsol(int x)
  22. {
  23. int sum=1,i,j;
  24. if((x<memSize-1) && (count[x]!=0 || x==0))
  25. return count[x];
  26. for(i=1;i<=x;i++)
  27. {
  28. for(j=1;j<=x/i;j++)
  29. {
  30. if(j*i + i-1 == x)
  31. sum+=noofsol(i-1);
  32. }
  33. }
  34. if(x<memSize-1)
  35. count[x]=sum;
  36. return sum;
  37. }
The original problem on codechef can be found here.
Note: This is a recursive solution. For achieving faster speed, you may convert it into iterative code.
If you want any clarification, please comment.
If you like this post please subscribe to this blog by email. You can also follow it.

Comments

Post a Comment

Popular posts from this blog

C Graph implementation with adjacency list representation using structures: Data Structure Tutorial 1

Accessing DynamoDB from Spring Java application - Walkthrough tutorial

Interview Of An Indian Top Coder : Rudradev Basak