Home » Scala programs » Scala basic programs

Scala program to find factorial of a number

Scala | Finding factorial of a Number: Here, we are going to learn how to find factorial of a given number in Scala programming language?
Submitted by Shivang Yadav, on April 21, 2020

Factorial of a number(n!) is the product of all positive numbers less than or equal to that number.

The formula for factorial of a number is,

    n! = n * (n-1) * (n-2) * ... * 2 * 1
    n! = 1 if n = 1 or 0

Based on the above formula we can generate a recursive formula,

    n! = n * (n-1)! 

Given a number, we have to find its factorial.

Example:

    Input: 
    n = 6

    Output: 
    n! = 720 

    Explanation:
    6! = 6*5*4*3*2*1 = 720

The program will use this formula to find the factorial. As find factorial is a repetitive process. We have two methods to solve this problem,

  1. Using iteration
  2. Using recursion

1) Recursive Approach to find factorial of a number

In recursion, we will call the same method multiple times until a condition is not satisfied.

Here, we will call the function factorial(n) in the following way:

Program:

object myObject {

    def factorialRec(n: Int): Int ={
        if(n <= 1)
            return 1
        return n * factorialRec(n-1)
    }
    
    def main(args: Array[String]) {
        val n = 6
        println("The factorial of " + n + " is " + factorialRec(n))
    }
}

Output

The factorial of 6 is 720

2) Iterative approach to find factorial of a number

In iteration, we will loop over a sequence of numbers and multiply the number to result variable to find factorial.

Program:

object myObject {
    def factorialIt(n: Int): Int ={
       var factorial = 1
       for(i <- 1 to n)
            factorial *= i
        return factorial
    }
    
    def main(args: Array[String]) {
        val n = 6
        println("The factorial of " + n + " is " + factorialIt(n))
        
    }
}

Output

The factorial of 6 is 720





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.