0

I'm trying to implement a program that returns the number of existing partitions of an integer n as part of an assignment. I wrote the code below, but it returns the wrong number (Partitions n returns the result of Partitions n-1). I don't get why this happens. I've tried many things and still don't know how to fix it, can anyone please help me?

[edited code out to avoid plagiarism from my colleagues :p]

m stands for the biggest number allowed in a partition, so partition(4,4) would be 5 = 4, 3+1, 2+2, 2+1+1, 1+1+1+1, but partition (4,1) would be 1 = 1+1+1+1. Execution: java Partitions n

7
  • 1
    @JacobG. A partition of a positive integer n is a way of writing n as a sum of positive integers. Two sums that differ only in the order of their summands are considered the same partition. more here: en.wikipedia.org/wiki/Partition_(number_theory) Commented Jun 4, 2017 at 22:22
  • 1
    else if (n <= 1 | m == 1) should probably be else if (n <= 1 || m == 1) Commented Jun 4, 2017 at 22:23
  • 2
    @KevinO that should not affect the program's behavior Commented Jun 4, 2017 at 22:26
  • 1
    You've written partition as a function of two integers n and m (besides the memoization array, which also stores a function of two integers). I'm sure you had a good reason for this, but the rest of us don't know what the definition of your partition(n,m) is. Commented Jun 4, 2017 at 22:29
  • 1
    I'm editing the question to clarify it. m stands for the biggest number in the partition, so partition(5, 5) would be 7 = 5, 4 +1, ... 1 + 1 + 1 + 1 + 1 and partition (5, 1) would be 1 = 1 + 1 + 1 + 1 + 1 I did it because the assignment is a derivation from introcs.cs.princeton.edu/java/23recursion/Partition.java.html and they do that there Commented Jun 4, 2017 at 22:34

1 Answer 1

2

Suppose you're calling partitions(4,4,memo). As you said, the answer should be 5 because there are 5 ways to partition the integer:

4
3 + 1           <== counted by partition(1,3,memo)
2 + 2           <== counted by partition(2,2,memo)
2 + 1 + 1       <== counted by partition(2,2,memo)
1 + 1 + 1 + 1   <== counted by partition(3,1,memo)

So it looks like your algorithm tries to count the partitions in the way shown above... but is there one partition you're forgetting to count?

Sign up to request clarification or add additional context in comments.

2 Comments

Please be careful about how you fix it--my first attempt didn't work when I tried it. In particular, partition(4,2) needs to return 3.
the simple way to solve it would be adding 1 to n right after parsing it in main, but i'm guessing that's the lazy way. i'm trying to find another one now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.