Skip to main content

Prime, Fibonacci and Factorial number with example in java

Prime number, Fibonacci series and Factorial number programs are most commonly asked questions in interview. Read this article to know what is and how to write programs for prime number, fibonacci series and factorial number.

Prime Number: prime number is natural number greater than 1 that has no positive divisor other than 1 and itself. A natural number greater than 1 is not a prime number, is called Composite number. For example, 7 is a prime number. Because it can divide with 1 and 7 only. Where as 8 is composite number. Since it has the divisor 2 and 4 in addition to the 1 and 8.

The below example represents the finding the passing number is prime number or not. If the passing number is prime number it will print true otherwise it will print false.

package com.javatbrains.practice;

public class PrimeNumber {
     public boolean isPrimeNumber(int number) {
          if(number <= 1)
             return false;

           // There's only one even prime: that is two
           if((number % 2) == 0)
             return(number == 2);

           int from = (int) (Math.sqrt(number) + 1);

           // You have to check possible divisors from 3 to sqrt(value)
           for(int i = 3; i <= from; i += 2)
             if((number % i) == 0)
               return false;

           return true;
     }

     public static void main(String args[]) {
          PrimeNumber prime = new PrimeNumber();
          System.out.println("11 is prime or not? "+ prime.isPrimeNumber(11));
          System.out.println("13 is prime or not? "+ prime.isPrimeNumber(13));
          System.out.println("15 is prime or not? "+ prime.isPrimeNumber(15));
     }
}
OutPut:
     11 is prime or not? true
     13 is prime or not? true
     15 is prime or not? false

Here is the another example to find the given number is prime or not. But, the logic and returning output will differ from above example.

package com.javatbrains.practice;

public class PrimeNumber {
     public String isPrimeNumber(int number) {
          String isPrime = "Prime";
          for(int j=2;j<number;j++){
              if(number%j==0){
                   isPrime = "Not Prime";
                   break;
              }
          }
          returnisPrime;
         
     }

     publicstaticvoidmain(String args[]) {
          PrimeNumber prime = new PrimeNumber();
          System.out.println("11 is prime or not? "+ prime.isPrimeNumber(11));
          System.out.println("13 is prime or not? "+ prime.isPrimeNumber(13));
          System.out.println("15 is prime or not? "+ prime.isPrimeNumber(15));
     }
}
OutPut:
     11 is prime or not? Prime
     13 is prime or not? Prime
     15 is prime or not? Not Prime

The below program will help you to identify and print the primitive numbers from 1 to 100 range. It also print total number of primitive numbers exists between 1 to 100.

packagecom.javatbrains.practice;

public class FindAllPrimeNumbers {

     static int limit= 100;
     static int count= 0;

     public static void main(String[] args) {

          for(int i=1;i<limit;i++){
              boolean isPrime = true;
              for(int j=2;j<i;j++){
                   if(i%j==0){
                        isPrime = false;
                        break;
                   }
              }

              if(isPrime){
                   count++;
                   System.out.print(i+", ");
              }
          }
          System.out.println();
          System.out.println("Total Prime Numbers between 1 to "+limit+": "+count);

     }

}

OutPut:
     1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
     53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 
     Total Prime Numbers between 1 to 100: 26

Fibonacci Number: Sum of the previous two numbers is called Fibonacci number. It has multiple synonyms like Fibonacci Series and Fibonacci sequence. The first two numbers in the sequence is 0 and 1. The following integer sequence represents the Fibonacci sequence as 0,1,1,2,3,5,8,13,21,34...etc. The below program will produces output as first 10 Fibonacci numbers starting from 0.

package com.javatbrains.practice;

public class Fibonacci {

     public static void main(String[] args) {
          int prev = 0, next = 1, sum, n;

          for(n = 1; n <= 10; n++) {
              System.out.print(prev+", ");
              sum = prev + next;
              prev = next;
              next = sum;
          }
     }

}

OutPut:
     0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

The below example will produces the similar output of the previous example. But, implementation logic will differ from previous program.

package com.javatbrains.practice;

public class Fibonacci {

     public static void main(String[] args) {
       int febCount = 10;
         int feb[] = new int[febCount];
         feb[0] = 0;
         feb[1] = 1;
         for(int i = 2; i<febCount; i++){
               feb[i] = feb[i-1]+feb[i-2];
         }
         for(int i=0; i<febCount; i++){
               System.out.print(feb[i]+", ");
         }
     }
}

OutPut:
     0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

The below example will find and print all Fibonacci numbers which value is lessthan 100. Please have a look at the below source code to understand more.

package com.javatbrains.practice;

public class Fibonacci {

 public static void main(String[] args) {
  int feb[] = new int[15];
  feb[0] = 0;
  feb[1] = 1;
  for (int i = 2; i < 100; i++) {
   if (feb[i - 1] + feb[i - 2] < 100) {
    feb[i] = feb[i - 1] + feb[i - 2];
   } else {
    break;
   }
  }
  for (int i = 0; i < feb.length; i++) {
   if (i == 0 || feb[i] > 0) {
    System.out.print(feb[i] + ", ");
   }
  }
 }
}
Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

Factorial Number: The product of the natural numbers from 1 to the given number is called the factorial number. There is a small Math formula to understand before going into program. Factorial formula is,

       n! =  1*2*3*.....*(n-1)*n

In the above formula, n represents the which you are passing the natural number for finding the factorial number. There are two different ways of calculating factorial number of a given number. Those are with recursion and without recursion. The below program illustrates, finding factorial number without using recursion.

package com.javatbrains.practice;

public class Factorial {

     public static void main(String[] args) {
          int n = 6;
          int fact=1;
         
          for(int i=1;i<=n;i++){
               //Factorial formula
              fact = fact*i;
          }
         
          System.out.println("Factorial of 6 is: "+fact);
     }

}

OutPut:
     Factorial of 6 is: 720

Factorial using Recursion: This is the another way of finding factorial of a given number using recursion. What is recursion? a function calls itself is called recursion. Below is the formula of finding factorial using recursion.

       fact(n) = n * fact(n-1);

The program will help you to find the factorial number of a given number by using the recursion.

package com.javatbrains.practice;

public class RecursionFactorial {

     public static void main(String[] args) {
          int n = 6;
          intfact = recursionFactorial(n);
          System.out.println("Factorial number of "+n+"is: "+fact);
     }
    
     public static int recursionFactorial(int n){
          if(n==0){
              return1;
          }else{
              returnn * recursionFactorial(n-1);   
          }
     }
}

OutPut:
     Factorial number of 6 is: 720










Comments

  1. factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.
    factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.
    factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.

    ReplyDelete

Post a Comment

Popular posts from this blog

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...