Skip to content

Commit

Permalink
Fibonacci and Factorial
Browse files Browse the repository at this point in the history
  • Loading branch information
AnujSaha0111 authored Oct 7, 2024
1 parent 56c0a07 commit a9bde61
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 0 deletions.
22 changes: 22 additions & 0 deletions Factorial.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import java.util.*;

public class Factorial {
public static void calculateFactorial(int n) {
if (n < 0) {
System.out.println("Invalid Number");
return;
}
int factorial = 1;
for (int i = n; i >= 1; i--) {
factorial = factorial * i;
}
System.out.println(factorial);
return;
}

public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
calculateFactorial(n);
}
}
15 changes: 15 additions & 0 deletions FactorialByRecursion.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
public class FactorialByRecursion {
public static int calcfactorial(int n) {
if (n == 1 || n == 0) {
return 1;
}
int fact_nm1 = calcfactorial(n-1);
int fact_n = n * fact_nm1;
return fact_n;
}
public static void main(String args[]) {
int n = 5;
int ans = calcfactorial(n);
System.out.println(ans);
}
}
29 changes: 29 additions & 0 deletions Fibonacci.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import java.util.*;

public class Fibonacci {
public static int printFibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
int a = 0, b = 1, result = 0;
for (int i = 2; i <= n; i++) {
result = a + b;
a = b;
b = result;
}
return result;
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of terms in the fibonacci series : ");
int n = sc.nextInt();
System.out.println("Fibonacci series up to " + n + " terms : ");
for (int i = 0; i <n; i++) {
System.out.print(printFibonacci(i) + " ");
}
sc.close();
}
}
17 changes: 17 additions & 0 deletions FibonacciByRecursion.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
public class FibonacciByRecursion {
public static void printFib(int a, int b, int n) {
if (n == 0) {
return;
}
int c = a + b;
System.out.println(c);
printFib(b, c, n - 1);
}
public static void main(String args[]) {
int a = 0, b = 1;
System.out.println(a);
System.out.println(b);
int n = 7;
printFib(a, b, n - 2);
}
}

0 comments on commit a9bde61

Please sign in to comment.