3 Replies - 300 Views - Last Post: 30 July 2014 - 02:28 AM Rate Topic: -----

#1 blackalbus7  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 29-July 14

factorial of large numbers

Posted 29 July 2014 - 02:20 PM

i have been doing coding challenges and while practicing i have encountered a problem and didn't know how to solve it.

by following some tutorials i have designed a code and still i dont get the desired output can anyone point out the bug
#include <iostream>

using namespace std;

int fact(int,int);

int arr[200]={1};

int main()
{
	int n,t,len=0,i=0,j,a;
	cin>>t;

	while(t--)
	{
		cin>>n;		
		a=n;
		while(a>0)
		{
			arr[i]=a%10;
			a=a/10;
			len++;
			i++;
		}
		cout<<len<<endl;
		len=fact(n,len);
		cout<<len<<endl;
		for(j=len-1;j>0;j--)
		{
			cout<<arr[j]<<endl;
		}
	}
	return 0;
}

int fact(int p,int m)
{
	int temp=0,i=0,x;
	while(i<=m)
	{
		if((i+1)>m && temp>0)
		{
			arr[i]=temp%10;
			temp=temp/10;
			m++;
			i++;
			if(temp==0)
			{
				break;
			}
		}
		else
		{
			x=arr[i]*(p-1)+temp;
			arr[i]=x%10;
			temp=temp/10;
			i++;
		}
	}
	if(p>2)
		fact(p-1,m);
	else
		return m;
}



Is This A Good Question/Topic? 0
  • +

Replies To: factorial of large numbers

#2 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9204
  • View blog
  • Posts: 34,581
  • Joined: 12-June 08

Re: factorial of large numbers

Posted 29 July 2014 - 02:23 PM

Quote

i dont get the desired output can anyone point out the bug

Explain! Explain any errors you are receiving.. Explain what you want your code to do, and explain what it is doing.
Was This Post Helpful? 0
  • +
  • -

#3 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2990
  • Posts: 10,329
  • Joined: 08-August 08

Re: factorial of large numbers

Posted 29 July 2014 - 05:29 PM

Factorials of large numbers can overflow int. Try unsigned long long.
Was This Post Helpful? 0
  • +
  • -

#4 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: factorial of large numbers

Posted 30 July 2014 - 02:28 AM

What you really need ... is ... a BigInt class ...

and ...
if your check at my signature web links (below) you will find several simple examples there.

Or Google ...
Big Numbers ... Big Int (Integers) ... via a C++ class David

This post has been edited by David W: 30 July 2014 - 02:33 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1