Click here to Skip to main content
15,889,116 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Question:
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Answer:

I did debug the code by taking the example of rowIndex as 3

Error:
Line 23: Char 29: runtime error: signed integer overflow: 479001600 * 13 cannot be represented in type 'int' [solution.c]

What I have tried:

C++
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
    int* getRow(int rowIndex, int* returnSize){
        int n=rowIndex;
        int r=0;
         int *p=(int*)malloc(sizeof(int)*(rowIndex+1));
            for(r=0;r<rowIndex+1;r++)
        {
            p[r]=1;
            if(r==0 || r==n)
            {
                 p[r]=1;
            }  
            else
            {
                int product=1;
                int k,s,t=1;
                k=r+1;
                while(k<=n )
                  {

                     product=product*k;
                     k++;
                  }
                p[r]=product;
                if(n-r!=0)
                  {
                      s=n-r;
                      while(s>1)
                         {
                           t=t*s;
                            s--;
                         }  
                  }
                       p[r]=p[r]/t;        
        }
            }
             *returnSize=rowIndex+1;
                 return p;
    } 
Posted
Updated 24-Jun-21 5:21am

The error message means precisely what it says: 479,001,600 × 13 is 6,227,020,800, whereas a signed 32-bit integer cannot hold a value larger than 2,147,483,647.

Just as you can't pour a pint into a half-pint glass, you can't store a 64-bit value in a 32-bit variable. At least not without overflowing the storage space.
 
Share this answer
 
Comments
KarstenK 24-Jun-21 11:22am    
that alcohol abuse and forbidden ;-)
_-_-_-me 24-Jun-21 11:31am    
Thank you!
Such overflows mostly occur when some bug like incomplete loop termination or bogous input like negative numbers occurs.

tip: use unsigned integers for all index parameters and check for some approbiate maximal number and debug your code to see what is going on.
 
Share this answer
 
Comments
_-_-_-me 24-Jun-21 11:30am    
Okay, thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900