Numbers

1. Check whether the given positive number is odd or even

1. With using condition

2. Without using condition

2. Swap two numbers
class SwapNumber{
 //Swap two numbers with using third variable(temp)
 public void swap(int x,int y){
  int temp=x;
  x=y;
  y=temp;
  System.out.println("After swap\nx= "+x+" y= "+y);
 }
 
 //Swap two numbers without using third variable
 public void swapWithoutTemp(int x,int y){
  x=x+y;
  y=x-y;
  x=x-y;
  System.out.println("After swap\nx= "+x+" y= "+y);
 }
 public static void swapNumbers (int x, int y)
 {
  x = x^y; 
  y = x^y; 
  x = x^y; 
  System.out.println("After swap\nx= "+x+" y= "+y);
 }
 public static void swapNum(int x, int y)
 {
  x = x*y; 
  y = x/y; 
  x = x/y; 
  System.out.println("After swap\nx= "+x+" y= "+y);
 }
 public static void main(String args[]){
  int x=10;
  int y=30;
  SwapNumber swapNumber=new SwapNumber();
  System.out.println("Before swap\nx= "+x+" y= "+y);
  swapNumber.swapWithoutTemp(x,y);
  System.out.println("\nBefore swap\nx= "+x+" y= "+y);
  swapNumber.swap(x,y);
  System.out.println("\nBefore swap\nx= "+x+" y= "+y);
  swapNumber.swapNumbers(x,y);
  System.out.println("\nBefore swap\nx= "+x+" y= "+y);
  swapNumber.swapNum(x,y);

 }
}
3. Check whether the given positive number is prime or not
4. Calculate factorial of given positive number

1. Using iteration

class Factorial{
  
 public static long calculateFactorial(int n){
  long fact=1;  
  if (n < 0) 
            throw new IllegalArgumentException("n must be >= 0");   
  for(int i=1;i<=n;i++){
   fact*=i;
  }
  return fact;
 }
 
 public static void main(String args[]){
  System.out.println(calculateFactorial(0));
  System.out.println(calculateFactorial(6));
  System.out.println(calculateFactorial(25));
  System.out.println(calculateFactorial(26));
  System.out.println(factorial(-5));
 }
}

2. Using recursion

class Factorial{
  
 public static long factorial(int n){
  if (n < 0) 
            throw new IllegalArgumentException("n must be >= 0");   
  if(n==0 || n==1){
   return 1;
  }
  else{
   return n*factorial(n-1);
  }
 }
 
 public static void main(String args[]){
  System.out.println(factorial(0));
  System.out.println(factorial(6));
  System.out.println(factorial(25));
  System.out.println(factorial(26));
  System.out.println(factorial(-3));
 }
}

3. Using BigInteger for big integer number

import java.math.BigInteger;
class Factorial{

 public static BigInteger factorial(int n){
  BigInteger fact=new BigInteger("1");
  for(int i=1;i<=n;i++)
  fact=fact.multiply(new BigInteger(i+""));
  return fact;
 }

 public static void main(String args[]){
  System.out.println(factorial(632));
  System.out.println(factorial(1224));
 }
}

0 comments:

Post a Comment

Search This Blog

Powered by Blogger.