Tuesday, June 4, 2013

Program to find out Primorial(P#) of a number

PROGRAM
Primorial(P#) is defined to be the product of prime numbers less than or equal to P. e.g.
3# = 2*3=6
5# = 2*3*5=30
13# = 2*3*5*7*11*13=30030
This is also called p-prime-factorial.
WAP to input a number and print its primordial i.e. n#
SAMPLE DATA
Enter a number=13
13#=2*3*5*7*11*13=30030
---------------------------------------------------------------------------------------------------------------------

/**
 * class primorial finds the primorial of a given number.
 * @author: Nitendra Kumar
 * @version: June 4/2013
 */
import java.util.Scanner;
public class primorial
{
  public int num=0;
  public void getnum()  //method to accept number from user
  {
      Scanner in=new Scanner(System.in);  //creating object of Scanner class
      System.out.println("Enter a number");
      num=in.nextInt();
    }
    public void findprimorial()  //method to find out primorial
    {
        int res=2,flag=0;
        String str="2";
        for(int i=3;i<=num;i++)
        {
         flag=0;
        for(int j=2;j<i;j++)
        {
           if(i%j==0)
            {
                flag=1;
                break;
            }
        }
        if(flag!=1)
        {
        res*=i;
        str=str+ "*" +i;      
        }
    }
       System.out.println(num +"#= " +str +"=" +res);
    }
    
    public static void main()
    {
        primorial ob=new primorial();  //creating object of primorial class
        ob.getnum();                   //calling method
        ob.findprimorial();            //calling method
    }
   
}

OUTPUT:

Enter a number
13
13#= 2*3*5*7*11*13=30030


/*---------------Program developed by: Nitendra Kumar---------------*/
//For more details visit http://javawithnitendra.blogspot.in


4 comments:

  1. I did not understand the logic of the program sir. Can you help me out ?

    ReplyDelete
    Replies
    1. Hi Tanmay..thanx fr showing ur intrst in my blog.
      plz read the concept of primorial it says "Primorial(P#) is defined to be the product of prime numbers less than or equal to P". So this program is finding out the product of prime nos less than or equal to P. The program is simple but if u still find any confusion plz comment...

      Delete
  2. What are we using the flag and res variables for ??

    ReplyDelete
  3. hello can u tell me how to write the algorithm

    ReplyDelete

Ur comments r most welcome...