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,

- Using iteration
- 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

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

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