function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Yash BhutaniYash Bhutani 

Write an apex program to print factorial

Best Answer chosen by Yash Bhutani
syed jabeenasyed jabeena
Hi Yash,

Please try the below one:
Type the code in Developer Console  and Exceute It

Factorial program:

public class sample 
{
public void fact(Integer n)
{
    long ans = 1;
    if (n < 0) {
        System.debug('No negative numbers');
    }
    else
    {
    for (Integer i = 1; i <= n; i++) {
        ans *= i;
    }
    }
  System.debug(ans);

    }
}

Press Ctrl+E and Type it

sample s=new sample();
s.fact(5);

Please Mark As a Best Answer.. If it was helpul to you..

Thanks & Regards,
Syed Jabeena

 

All Answers

SwethaSwetha (Salesforce Developers) 
HI Yash,
You can use the code from https://salesforceforfresher.wordpress.com/2021/06/13/factorial-salesforce-apex-trigger/
 
trigger MathCal on MPC__c (before Insert, before Update) {
    for(MPC__c  m : Trigger.new)
    {
       if(trigger.isInsert || trigger.isUpdate)
        {
   
   long fac=1;

   for(integer j = 1; j<= m.Factorial__c; j++) {
      fac = fac * j;
   }
   
   m.Output_of_the_Factorial__c = 'Factorial of ' + m.Factorial__c + ' = ' + fac;

    }
  }
}
Also see related post: https://developer.salesforce.com/forums/?id=9060G0000005ZujQAE

Some basic code snippets: https://webkul.com/blog/apex-programming-basics/

If this information helps, please mark the answer as best. Thank you
syed jabeenasyed jabeena
Hi Yash,

Please try the below one:
Type the code in Developer Console  and Exceute It

Factorial program:

public class sample 
{
public void fact(Integer n)
{
    long ans = 1;
    if (n < 0) {
        System.debug('No negative numbers');
    }
    else
    {
    for (Integer i = 1; i <= n; i++) {
        ans *= i;
    }
    }
  System.debug(ans);

    }
}

Press Ctrl+E and Type it

sample s=new sample();
s.fact(5);

Please Mark As a Best Answer.. If it was helpul to you..

Thanks & Regards,
Syed Jabeena

 
This was selected as the best answer