This angular tutorial help to create a script for Factorial, Fibonacci, Prime and Even/Odd. You can use these code for angular 13 as well.
There are some common programming interview questions asked by an interviewer to check logic. These questions are asked to beginners/freshers as well as mid-level programmers.
We will share angular 13 script code for following problems:
- Factorial using recursive manner
- n prime number in angular 13
- How to generate n number Fibonacci in angular 13
- Check number is even or odd in Angular 13
You can implement the same logic for JavaScript, Angular 1.4/9/12 and angular 13. There might be some syntax different for angular 1.4 and JavaScript. You can use the angular 13 switches conditional statement to execute a specific method, based on the parameter passed to the switch method.
Program of Factorial using Recursive Method in Angular 13
A factorial is a product of all the numbers from 1 to the user-specified number. We will pass n as the parameter that limits the number of factorials. If the passed parameter value is 0 then the factorial value would be 1. Below is the source code of the angular 13 program to print the factorial of a given number in the console.
4 number factorial is : 1X2X3X4 = 24
factorial(n) { if (n === 0) { return 1; } // This is it! Recursion!! return n * this.factorial(n - 1); } get_factorial(n) { console.log(this.factorial(n)); }
Program of Fibonacci Number in Angular 13
The Fibonacci sequence is a series where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1.
The Fibonacci sequence of 4 : 0, 1, 1, 2, 3, 5
fibonacci_series(n) { var i : any; var a = 0, b = 1, f = 1; for(i = 2; i <= n; i++) { f = a + b; a = b; b = f; console.log(f); this.fibos.push(f); } };
We have to use angular 13 for loop to generate the next Fibonacci number and swap variable values.
Program of Prime Number in Angular4
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
The Prime sequence of 4 : 2, 3
prime_series(n) { var i : any; var j : any; var notPrime : boolean; notPrime = false; for (i = 1; i <= n; i++) { for(j = 2; j<= i; j++) { if (i%j === 0 && j!==i) { notPrime = true; } } if(!notPrime) { this.prime.push(i); } } console.log(this.prime); }
We have used 13 angulars for loops to check prime numbers and stored them into a variable.
Program to Check Even/Odd Number in Angular 13
The even number are those numbers that are divided by 2 and the rest of them are odd.
The Even Number are : 2, 4, 6 …
The Even Number are : 1, 3, 5 …
The following Angular 13 code help to check passed number is even or odd.
check_even(n) { console.log(n); if(n/2 === 0) { console.log(n+' is even'); } else { console.log(n+ ' is odd'); } }