Write a Java program to accept number from user and Calculate factorial of given number and Also check whether given number is prime or not. (Use Thread)
Write a Java program to accept number from user and Calculate factorial of given number and Also check whether given number is prime or not. (Use Thread)
Program:
import java.io.*; import java.lang.*; class FactPrime extends Thread { String str; int num1, num2, fact=1, flag=1, i; FactPrime(String s, int n) { num1 = n; str = s; setName(str); start(); } public void run() { if(str.equals("First")) { try { for(i=1; i<=num1; i++) { fact = fact*i; sleep(500); } System.out.println("Factorial: "+fact); } catch (InterruptedException e) { System.out.println(e); } } else if(str.equals("Second")) { try { for(i=2;i<num1;i++) { if(num1%i==0){ flag = 0; break; } sleep(500); } if(flag==0){ System.out.println("Number is not Prime."); } else{ System.out.println("Number is Prime."); } } catch(InterruptedException e){ System.out.println(e); } } } } class ThreadFactPrime { public static void main(String args[]) { int n,m; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the number to calculate Factorial:"); n=Integer.parseInt(br.readLine()); FactPrime t1 = new FactPrime("First",n); m=Integer.parseInt(br.readLine()); FactPrime t2 = new FactPrime("Second",m); } }
Comments
Post a Comment