Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6580523
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T16:02:24+00:00 2026-05-25T16:02:24+00:00

Suppose I have a method to calculate combinations of r items from n items:

  • 0

Suppose I have a method to calculate combinations of r items from n items:

    public static long combi(int n, int r) {

        if ( r == n) return 1;
        long numr = 1;
        for(int i=n; i > (n-r); i--) {
            numr *=i;

        }
        return numr/fact(r);

    }


public static long fact(int n) {

        long rs = 1;
        if(n <2) return 1;
        for (int i=2; i<=n; i++) {
            rs *=i;
        }
        return rs;

    }

As you can see it involves factorial which can easily overflow the result. For example if I have fact(200) for the foctorial method I get zero. The question is why do I get zero?

Secondly how do I deal with overflow in above context? The method should return largest possible number to fit in long if the result is too big instead of returning wrong answer.

One approach (but this could be wrong) is that if the result exceed some large number for example 1,400,000,000 then return remainder of result modulo
1,400,000,001. Can you explain what this means and how can I do that in Java?

Note that I do not guarantee that above methods are accurate for calculating factorial and combinations. Extra bonus if you can find errors and correct them.

Note that I can only use int or long and if it is unavoidable, can also use double. Other data types are not allowed.

I am not sure who marked this question as homework. This is NOT homework. I wish it was homework and i was back to future, young student at university. But I am old with more than 10 years working as programmer. I just want to practice developing highly optimized solutions in Java. In our times at university, Internet did not even exist. Today’s students are lucky that they can even post their homework on site like SO.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T16:02:25+00:00Added an answer on May 25, 2026 at 4:02 pm

    To answer your first question (why did you get zero), the values of fact() as computed by modular arithmetic were such that you hit a result with all 64 bits zero! Change your fact code to this:

    public static long fact(int n) {
        long rs = 1;
        if( n <2) return 1;
        for (int i=2; i<=n; i++) {
            rs *=i;
            System.out.println(rs);
        }
        return rs;
    }
    

    Take a look at the outputs! They are very interesting.

    Now onto the second question….

    It looks like you want to give exact integer (er, long) answers for values of n and r that fit, and throw an exception if they do not. This is a fair exercise.

    To do this properly you should not use factorial at all. The trick is to recognize that C(n,r) can be computed incrementally by adding terms. This can be done using recursion with memoization, or by the multiplicative formula mentioned by Stefan Kendall.

    As you accumulate the results into a long variable that you will use for your answer, check the value after each addition to see if it goes negative. When it does, throw an exception. If it stays positive, you can safely return your accumulated result as your answer.

    To see why this works consider Pascal’s triangle

    1
    1  1
    1  2   1
    1  3   3   1
    1  4   6   4   1
    1  5  10  10   5  1
    1  6  15  20  15  6  1
    

    which is generated like so:

    C(0,0) = 1 (base case)
    C(1,0) = 1 (base case)
    C(1,1) = 1 (base case) 
    C(2,0) = 1 (base case) 
    C(2,1) = C(1,0) + C(1,1) = 2
    C(2,2) = 1 (base case)
    C(3,0) = 1 (base case)
    C(3,1) = C(2,0) + C(2,1) = 3
    C(3,2) = C(2,1) + C(2,2) = 3
    ...
    

    When computing the value of C(n,r) using memoization, store the results of recursive invocations as you encounter them in a suitable structure such as an array or hashmap. Each value is the sum of two smaller numbers. The numbers start small and are always positive. Whenever you compute a new value (let’s call it a subterm) you are adding smaller positive numbers. Recall from your computer organization class that whenever you add two modular positive numbers, there is an overflow if and only if the sum is negative. It only takes one overflow in the whole process for you to know that the C(n,r) you are looking for is too large.

    This line of argument could be turned into a nice inductive proof, but that might be for another assignment, and perhaps another StackExchange site.

    ADDENDUM

    Here is a complete application you can run. (I haven’t figured out how to get Java to run on codepad and ideone).

    /**
     * A demo showing how to do combinations using recursion and memoization, while detecting
     * results that cannot fit in 64 bits.
     */
    public class CombinationExample {
    
        /**
         * Returns the number of combinatios of r things out of n total.
         */
        public static long combi(int n, int r) {
            long[][] cache = new long[n + 1][n + 1];
            if (n < 0 || r > n) {
                throw new IllegalArgumentException("Nonsense args");
            }
            return c(n, r, cache);
        }
    
        /**
         * Recursive helper for combi.
         */
        private static long c(int n, int r, long[][] cache) {
            if (r == 0 || r == n) {
                return cache[n][r] = 1;
            } else if (cache[n][r] != 0) {
                return cache[n][r];
            } else {
                cache[n][r] = c(n-1, r-1, cache) + c(n-1, r, cache);
                if (cache[n][r] < 0) {
                    throw new RuntimeException("Woops too big");
                }
                return cache[n][r];
            }
        }
    
        /**
         * Prints out a few example invocations.
         */
        public static void main(String[] args) {
            String[] data = ("0,0,3,1,4,4,5,2,10,0,10,10,10,4,9,7,70,8,295,100," +
                    "34,88,-2,7,9,-1,90,0,90,1,90,2,90,3,90,8,90,24").split(",");
            for (int i = 0; i < data.length; i += 2) {
                int n = Integer.valueOf(data[i]);
                int r = Integer.valueOf(data[i + 1]);
                System.out.printf("C(%d,%d) = ", n, r);
                try {
                    System.out.println(combi(n, r));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    }
    

    Hope it is useful. It’s just a quick hack so you might want to clean it up a little…. Also note that a good solution would use proper unit testing, although this code does give nice output.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Suppose I have a method that must return an object (say from a database
Suppose you have a method like public Something copy () { return new Something();
Suppose I have a method public Patient(int id) { ---- } that returns Patient
Suppose I have a method like so: public byte[] GetThoseBytes() { using (System.IO.MemoryStream ms
Suppose I have a static method of my class that returns an object of
Suppose I have the following method signature int f (int[] values) and I call
Suppose we have two overridden versions of a method. One accepts int as argument
Suppose I have a method like: def calculate(alpha, beta) # do stuff end How
Let me provide an example: Suppose i have a method: public void DoStuff(IEnumerable<T> sequence)
I have a method that that is suppose to calculate the bearing between two

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.