473,796 Members | 2,720 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Function for Factorial.

Hi.
How to write a function that will return me the factorial (say in a string)
for the any positive integer it takes?

When we find a factorial of even say 2000 or a higher number, it will be
very big to be accomodated in int or long datatype.

Regards,
Sugandh
Apr 30 '07 #1
3 8017
You can write a recursive function, which I've illustrated below:

Note, however, that I'm using the largest positive integer data type
(Uint64), and that you can only get values for numbers up to 21 with it.
Anything larger throws an overflow exception, as the result is larger than
UInt64.MaxValue .

To calculate larger numbers, you would need to create your own integral data
type, with storage larger than 64 bits.

/// <summary>
/// Returns the factorial of any UInt64 less than 22
/// </summary>
/// <param name="n">The number to get a factorial for.</param>
/// <returns>The factorial of n.</returns>
/// <remarks>Thro ws an exception if the number passed is greater than
21</remarks>
public static UInt64 Factorial(UInt6 4 n)
{
UInt64 i = Factorial(n - 1, 0);
return i;
}

/// <summary>
/// Returns the factorial of any UInt64 less than 22
/// </summary>
/// <param name="n">The number to get a factorial for.</param>
/// <param name="ct">The count of iterations</param>
/// <returns>The factorial of n.</returns>
/// <remarks>Thro ws an exception if the number passed is greater than
21</remarks>
private static UInt64 Factorial(UInt6 4 n, int ct)
{
if (n == 0) return 1;
if (n < 0) throw new Exception("Fact orials may not be determined for
negative numbers");
if (ct 21) throw new Exception("Too many recursion levels");
return n * Factorial(n - 1, ct + 1);
}

--
HTH,

Kevin Spencer
Microsoft MVP

Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net

"Sugandh Jain" <su**********@n irvana-sol.comwrote in message
news:eq******** ******@TK2MSFTN GP02.phx.gbl...
Hi.
How to write a function that will return me the factorial (say in a
string) for the any positive integer it takes?

When we find a factorial of even say 2000 or a higher number, it will be
very big to be accomodated in int or long datatype.

Regards,
Sugandh

Apr 30 '07 #2
Sugandh Jain wrote:
Hi.
How to write a function that will return me the factorial (say in a string)
for the any positive integer it takes?

When we find a factorial of even say 2000 or a higher number, it will be
very big to be accomodated in int or long datatype.

Regards,
Sugandh

The simplest way to fake this is to keep an array (of 16 or 32 bit ints) where
each member represents one decimal digit of your running result. To represent
n! you then simulate the multiplication one digit at a time with each new factor
1 through n. At the end each result digit can be converted to a string
representation. Tips: 1) initialize correctly and 2) don't forget the carry!

With 32 bit members you would in principle be good on the multiplication side
for over 200,000,000!; however you may find that you run out of memory for the
digit array somewhat before that . . .

HTH,
-rick-
Apr 30 '07 #3
Sugandh Jain wrote:
How to write a function that will return me the factorial (say in a string)
for the any positive integer it takes?

When we find a factorial of even say 2000 or a higher number, it will be
very big to be accomodated in int or long datatype.
You will need a biginteger class.

Google finds:
http://www.codeproject.com/csharp/biginteger.asp

Arne
Jun 9 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

39
7668
by: Mike MacSween | last post by:
Just spent a happy 10 mins trying to understand a function I wrote sometime ago. Then remembered that arguments are passed by reference, by default. Does the fact that this slowed me down indicate: a) That I don't know enough b) Passing arguments by ref is bad
11
4274
by: Martin Jørgensen | last post by:
Hi, Consider (factorial.cpp): #include <iostream> using namespace std; double R=3.2; /* not used, but R is static because it is a global variable (file scope) */
8
11362
by: salman | last post by:
this program is giving compile time error. so plse ge me the logic of factorial # include <iostream.h> # include <math.h> void main() { int f,sum=0,i,j,n; cout<<"\nEnter Number: ";
12
1469
by: C Barr Leigh | last post by:
Help! Have I found a serious bug? This seems like highly undesired behaviour to me. From the program below, I get output: call1: call2: call3: instead of what I should get,
17
8100
by: DanielJohnson | last post by:
how to use the combination function in python ? For example 9 choose 2 (written as 9C2) = 9!/7!*2!=36 Please help, I couldnt find the function through help.
0
25661
by: Killer42 | last post by:
Here's a very simple function for VB (written in VB6) to calculate the factorial (!) of a number. Note that it is limited by the magnitude of the value which can be stored in the Long data type. (In fact, I believe it overflows at 13!) Public Function Factorial(ByVal bNum As Byte) As Long Dim I As Long If bNum <= 0 Then Exit Function Factorial = 1 For I = 1 To bNum Factorial = Factorial * I Next End Function
34
1983
by: Umesh | last post by:
how to convert a program to a function/macro and put it in a header file? is there any shortcut method for this? thanks.
3
2975
by: Blue sky | last post by:
Hi,I am a new C++ learner.The follow prgram produces a wrong result,but I can't find the wrong.Can you help me?Thank you! #include<stdio.h> long factorial( long number); int main() { int a;
0
10449
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10217
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10168
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10003
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9047
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7546
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5440
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.