!Num (Number Factorial) lazarus / 21-General ---------------------------------------------------------------------- nikel · 2021-07-23 04:12 Hello, can I do this in pascal: When number is 3 I want it to multiply 3 to 1 (3 * 2 * 1). When number is 5 it should multiply 5 * 4 * 3 * 2 * 1 ---------------------------------------------------------------------- lucamar · 2021-07-23 04:47 Basic stuff, that Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function factorial(num: Integer): Integer;var  i: Integer;begin  Result := num;  for i := num-1 downto 1 do    Result := Result * i;end; ---------------------------------------------------------------------- 440bx · 2021-07-23 05:13 It would be good for a factorial function to ensure the number it received is greater than or equal to  zero (0) and, if it is zero, it should return 1 not zero ---------------------------------------------------------------------- nikel · 2021-07-23 05:49 Yes, that makes a number number. 1 * 0 = 0 (1 is a number) 200 * 0 = 0 (200 is a number) But 0 * 0 = nonsense ---------------------------------------------------------------------- lucamar · 2021-07-23 05:58 Quote from: 440bx on July 23, 2021, 07:13:16 am It would be good for a factorial function to ensure the number it received is greater than or equal to  zero (0) and, if it is zero, it should return 1 not zero You're right, of course, and I knew it. Don't know how I managed to skip it. And one should also check for negative numbers, which I forgot too ... ---------------------------------------------------------------------- Bart · 2021-07-23 09:01 Since factorials will blow up rather fast (at least if you use an integer type as result: Fac(20) = 2432902008176640000 (or $21C3677C82B40000, Fac(21) is greater than largest possible QWORD), you might as well make a lookup table. Bart ---------------------------------------------------------------------- lucamar · 2021-07-23 10:15 Quote from: Bart on July 23, 2021, 11:01:52 am[...] you might as well make a lookup table. Yes, but unless you're good at calculating factorials on your head you'd need a function such as the one I gave to calculate the LUT at least once in a lifetime. Though if one really needed to calculate factorials for a living I guess one would use some BigNum lib or such, like one does to calculate Pi or find primes or things like that Fact is the OP looks more like the tipical homework and I'm tempted to   replace the code in my first post for a nice explanation of how would go about building such a thing. My excuse is that it was around 7:00 after passing a night sleeping badly and I didn't think before replying. And it's such a basic thing ... ---------------------------------------------------------------------- Bart · 2021-07-23 11:44 Quote from: lucamar on July 23, 2021, 12:15:52 pmFact is the OP looks more like the tipical homework ... Yep, and (s)he will get extra points for a recursive version, which (s)he must implement her/himself  Bart ---------------------------------------------------------------------- lucamar · 2021-07-23 12:33 Quote from: Bart on July 23, 2021, 01:44:40 pmYep, and (s)he will get extra points for a recursive version, which (s)he must implement her/himself  Yeah, probably. Though I can't understand why people insist on implementing factorial recursively when a simple loop is more than enough. Factorials and similar operations must be the worst examples of recursive algorithms ---------------------------------------------------------------------- Jurassic Pork · 2021-07-23 13:14 hello, Quote from: Bart on July 23, 2021, 11:01:52 amSince factorials will blow up rather fast (at least if you use an integer type as result: Fac(20) = 2432902008176640000 (or $21C3677C82B40000, Fac(21) is greater than largest possible QWORD), you might as well make a lookup table. with gmp library you can calculate big number and you have a factorial fonction : Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure CalculateFactorial();Var R1 : mpz_t; resultat: String; P_resultat: Pchar;beginmpz_init(@R1);mpz_fac_ui(@R1,100);P_resultat := StrAlloc(1024);gmp_sprintf(P_resultat, '100! = %Zd', @R1);resultat := P_resultat;Form1.Memo1.Append(resultat);end; Result in attachment Friendly, J.P ---------------------------------------------------------------------- MarkMLl · 2021-07-23 13:18 Quote from: lucamar on July 23, 2021, 12:15:52 pmFact is the OP looks more like the tipical homework and I'm tempted to   replace the code in my first post for a nice explanation of how would go about building such a thing. My excuse is that it was around 7:00 after passing a night sleeping badly and I didn't think before replying. And it's such a basic thing ... Assuming that only one person is using the login ID zhe's been here for years doing a variety of stuff including databases etc., so this is unlikely to be homework. MarkMLl ---------------------------------------------------------------------- winni · 2021-07-23 13:34 Hi! Here is the beloved recursive version. What a nonsense... Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TForm1.Button1Click(Sender: TObject);var facStr : String;    fac,err: Integer;    facResult : Int64;     procedure factorial (num,maxnum: Integer; var fresult: Int64);    begin    if num <= maxnum then      begin      fresult := Fresult * num;      factorial (num+1,maxnum,Fresult);      end;     end; begin    facStr := InputBox('Factorial of:',    'Please type in', '');    val (facStr,fac,err);    if (err >0) or (fac<1) then      begin      ShowMessage ('Input error');      exit;   end;     facResult := 1;    factorial(1,fac,FacResult);    showMessage ('Result: '+IntToStr(FacResult));end; Winni ---------------------------------------------------------------------- lucamar · 2021-07-23 14:35 Quote from: MarkMLl on July 23, 2021, 03:18:22 pmAssuming that only one person is using the login ID zhe's been here for years doing a variety of stuff including databases etc., so this is unlikely to be homework. Where I abbreviated as OP I meant Original Post, which to me looks like the tipical exercise, but even so, the task is so basic that I can't think of an even moderately experienced programmer failing to do it without help, hence my assumption (strenghtened by his previous recent posts) that the original poster is if not an absolute beginner at least not very experienced. At least with Pascal. Of course, I might be wrong (and I am with distressing frequency lately); if so, my excuses to whoever might feel slighted, which was very far from my intention. Quote from: winni on July 23, 2021, 03:34:47 pmHere is the beloved recursive version. What a nonsense... [... etc ...] And here the "classical" one: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function factorial(const num: Int64): Int64;{ Just an example: no range checks, inappropiate types, etc. }begin  if num < 1 then    Result := 1  else    Result := num * factorial(num-1);end; Let's hope is not indeed homework; else we have just helped a student to cheat ... ---------------------------------------------------------------------- engkin · 2021-07-23 14:52 It might be worth mentioning that it is possible to use threads to increase the speed, assuming your CPU has suitable cores. And if accurate answer is not necessary, it is possible to use logarithms to do the calculations much faster. ---------------------------------------------------------------------- MarkMLl · 2021-07-23 15:04 Quote from: lucamar on July 23, 2021, 04:35:40 pmWhere I abbreviated as OP I meant Original Post, which to me looks like the tipical exercise, but even so, the task is so basic that I can't think of an even moderately experienced programmer failing to do it without help, hence my assumption (strenghtened by his previous recent posts) that the original poster is if not an absolute beginner at least not very experienced. At least with Pascal. Well, I'm notorious for casual intolerance but look through the user's posting history, which goes back ten years. Now it /might/ be a student borrowing a parents' old account, or somebody who's found a user ID and password somewhere on the web, but it looks far more like an occasional business user or similar in which case we should be grateful that zhe's persevering with Lazarus and Pascal. @nikel: what are you actually trying to do here? Are you trying to calculate n! as an end to itself, or are you trying to do some basic combinations/permutations stuff? MarkMLl ---------------------------------------------------------------------- winni · 2021-07-23 15:22 Quote from: lucamar on July 23, 2021, 04:35:40 pm Let's hope is not indeed homework; else we have just helped a student to cheat ...  Cheating  wont bring you far in math! That is the difference to buisines studies or jurisprudence. Winni ---------------------------------------------------------------------- Kays · 2021-07-23 15:47 Quote from: nikel on July 23, 2021, 06:12:07 amHello, can I do this in pascal: […]Yes, but there is no built-in support for that, you’ll need—as you already saw—either implement it on your own, or use some sort of library. I haven’t found nothing in the math unit. Quote from: Jurassic Pork on July 23, 2021, 03:14:19 pmwith gmp library you can calculate big number and you have a factorial fonction :Yes, I like that (using GMP). If you like you can also use them good old logarithms, yet it loses precision. On a 64-bit system with an 80-bit FPU, 20! is “already” slightly off. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program factorialFun(input, output, stdErr); function factorialLn(n: ALUUInt): valReal;begin        factorialLn := 0.0;                for n := n downto 2 do        begin                factorialLn := factorialLn + ln(n);        end;end; var        n: ALUUInt;begin        for n := 0 to 20 do        begin                writeLn(n:2, ' : ', round(exp(factorialLn(n))):20);        end;end.Yet this allows you (to some degree) calculate (or rather approximate) and use factorials that are too large for ALUUInt. Example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program lottery(input, output, stdErr); { function factorialLn as defined above } function binomialCoefficient(n, k: ALUUint): ALUUint;begin      binomialCoefficient := round(exp(                        factorialLn(n) -                        (factorialLn(k) + factorialLn(n - k))                ));end; begin        writeLn('Germany:':20, binomialCoefficient(49, 6):20);        writeLn('US (MM):':20, binomialCoefficient(75, 5):20);end.NB: There are better algorithms to calculate the binomial coefficient. ---------------------------------------------------------------------- MarkMLl · 2021-07-23 17:15 Quote from: Kays on July 23, 2021, 05:47:35 pmNB: There are better algorithms to calculate the binomial coefficient. And there are more appropriate computational frameworks than a strictly-procedural language such as Pascal. I'm moderately confident that even late-60s APL could handle something like 50! / 49! because it delayed the actual evaluation until as late as possible. (Strictly, that would be written 49! ÷ 50! since evaluation was right- to-left.) MarkMLl ---------------------------------------------------------------------- BobDog · 2021-07-26 20:47 Without an external library, here is factorial of bigger numbers: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i    program fac;     usesSysUtils,DateUtils;  { only for the timer }     function factorial(num:longint):ansistring ;    type     AT = array[0..99] of longint;     var     _mod,_div:at;     fact,a,b,c:ansistring;     pa,pb,pc:pchar;     n,carry,ai:smallint;     la,lb,i,j,z:longint;     begin //create lookup  tables     for z:=0 to 99 do     begin     _mod[z]:= (z mod 10) +48;     _div[z]:=  z div 10;      end;  //created lookup tables        fact:='1';      for z:=1 to num do       begin       a:=fact;Str(z,b);la:=Length(a);lb:=length(b);       Setlength(c,la+lb);       FillChar(c[1],la+lb,#48);        pa:=@a[1]; //set pointers        pb:=@b[1];        pc:=@c[1];      for i:=la-1 downto 0 do      begin         carry:=0;ai:=ord(pa[i])-48 ;      for j:= lb-1 downto 0 do      begin        n :=ai*(ord(pb[j])-48)+(ord(pc[i+j+1])-48)+carry;        carry :=_Div[n];ord(pc[i+j+1]):=_Mod[n];      end;       ord(pc[i]):=ord(pc[i])+carry ;      end;      fact:=c;      if c[1]='0' then fact:=copy(c,2,length(c)-1) ;      end;       exit(fact);      end;  {===========  start ===========}      var    e:ansistring;    num:longint;  D1,D2: TDateTime;        begin       num:= 5000;       writeln('factotial ',num,'  =  ');       D1:=now;     e:=  factorial(num);       D2:=now;       writeln(e);       writeln( MilliSecondsBetween(D1, D2), ' milliseconds');       writeln('Press return to end . . .');       readln;       end.