Saturday, 6 April 2013

Important mathematical logic examples in Java



import java.util.Scanner;


public class Leap {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Please enter the number:");

int y = scanner.nextInt();

scanner.close();

if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) {

System.out.println("leap year");

} else {

System.out.println("Not leap year");

}

}

}

 =============================================
import java.util.Scanner;

public class Armstrong {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any number:");
        int n = sc.nextInt();
        sc.close();

        int sum = 0, temp = n;
        while (temp != 0) {
            int r = temp % 10;
            sum += r * r * r;
            temp /= 10;
        }

        if (n == sum) {
            System.out.println("The number is an Armstrong number.");
        } else {
            System.out.println("The number is not an Armstrong number.");
        }
    }
}

=================================
class ArithmeticOperations {
    private int a, b;

    public ArithmeticOperations(int a, int b) {
        this.a = a;
        this.b = b;
    }

    public int add() {
        return a + b;
    }

    public int subtract() {
        return a - b;
    }

    public int multiply() {
        return a * b;
    }

    public int divide() {
        if (b == 0) {
            throw new ArithmeticException("Division by zero is not allowed.");
        }
        return a / b;
    }

    public int modulo() {
        if (b == 0) {
            throw new ArithmeticException("Modulo by zero is not allowed.");
        }
        return a % b;
    }

    public void displayResults() {
        System.out.println("The value of a is: " + a);
        System.out.println("The value of b is: " + b);
        System.out.println("The sum is: " + add());
        System.out.println("The difference is: " + subtract());
        System.out.println("The product is: " + multiply());
        try {
            System.out.println("The quotient is: " + divide());
            System.out.println("The remainder is: " + modulo());
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }
    }
}

public class Arithmetic {
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Please enter two values.");
        } else {
            try {
                int n1 = Integer.parseInt(args[0]);
                int n2 = Integer.parseInt(args[1]);
                ArithmeticOperations ao = new ArithmeticOperations(n1, n2);
                ao.displayResults();
            } catch (NumberFormatException e) {
                System.out.println("Invalid input. Please enter two integer values.");
            }
        }
    }
}

 ==================================
import java.util.Scanner;

public class ArithmeticScanner {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter first value:");
        int a = sc.nextInt();
        System.out.println("Enter second value:");
        int b = sc.nextInt();
        sc.close();

        double add = add(a, b);
        double subtract = subtract(a, b);
        double multiply = multiply(a, b);
        double divide = divide(a, b);
        double modulo = modulo(a, b);
        double average = average(a, b);

        System.out.println("The sum is: "+add);
        System.out.println("The difference is: "+subtract);
        System.out.println("The product is: "+multiply);
        System.out.println("The quotient is: "+divide);
        System.out.println("The remainder is: "+modulo);
        System.out.println("The average is: "+average);
    }

    private static double add(int a, int b) {
        return a + b;
    }

    private static double subtract(int a, int b) {
        return a - b;
    }

    private static double multiply(int a, int b) {
        return a * b;
    }

    private static double divide(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("Division by zero is not allowed.");
        }
        return (double) a / b;
    }

    private static double modulo(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("Modulo by zero is not allowed.");
        }
        return a % b;
    }

    private static double average(int a, int b) {
        return (a + b) / 2.0;
    }
}

 =======================================
import java.util.Scanner;

public class AreaCalculator {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        calculateSquare(sc);
        calculateAverage(sc);
        calculateTriangle(sc);
        calculateCircle(sc);

        sc.close();
    }

    private static void calculateSquare(Scanner sc) {
        System.out.println("Enter side of square:");
        int side = sc.nextInt();
        double area = side * side;
        double perimeter = 4 * side;
        System.out.println("The given side is: " + side);
        System.out.println("The area of the square is: " + area);
        System.out.println("The perimeter of the square is: " + perimeter);
    }

    private static void calculateAverage(Scanner sc) {
        System.out.println("Enter three numbers:");
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        double average = (a + b + c) / 3.0;
        System.out.println("The average is: " + average);
    }

    private static void calculateTriangle(Scanner sc) {
        System.out.println("Enter base of triangle:");
        int base = sc.nextInt();
        System.out.println("Enter height of triangle:");
        int height = sc.nextInt();
        double area = 0.5 * base * height;
        System.out.println("The area of the triangle is: " + area);
    }

    private static void calculateCircle(Scanner sc) {
        System.out.println("Enter radius of circle:");
        int radius = sc.nextInt();
        double area = Math.PI * radius * radius;
        double circumference = 2 * Math.PI * radius;
        System.out.println("The given radius is: " + radius);
        System.out.println("The area of the circle is: " + area);
        System.out.println("The circumference of the circle is: " + circumference);
    }
}

 ================================

import java.util.Scanner;


public class SwapNumbers {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter two numbers:");

int a = sc.nextInt();

int b = sc.nextInt();

sc.close();


System.out.println("Before swapping: a = " + a + ", b = " + b);


// Swapping using arithmetic operations

a = a + b;

b = a - b;

a = a - b;


System.out.println("After swapping: a = " + a + ", b = " + b);

}

}

 ================================
import java.util.Scanner;

public class LargestOfThree {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter three numbers:");
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        sc.close();

        if (a >= b && a >= c) {
            System.out.println("The largest number is: " + a);
        } else if (b >= a && b >= c) {
            System.out.println("The largest number is: " + b);
        } else {
            System.out.println("The largest number is: " + c);
        }
    }
}

 ===================================
import java.util.Scanner;

public class SumOfDigits {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any number:");
        int n = sc.nextInt();
        sc.close();

        long sum = 0;
        while (n != 0) {
            int r = n % 10;
            sum += r;
            n /= 10;
        }

        System.out.println("The sum of the digits is: " + sum);
    }
}

 ================

import java.util.Scanner;


public class SumOfNumbers {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter one number:");

int n = sc.nextInt();

sc.close();


long sum = (long) n * (n + 1) / 2;

// for loop logic

// for (int i = 0; i <= n; i++) {

// sum += i;

// }


System.out.println("The sum is: " + sum);

}

}

 =================================

import java.util.Scanner;


public class NonRecursiveFibonacci {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of Fibonacci numbers to generate:");

int n = sc.nextInt();

sc.close();


int firstFibonacci = 1;

int secondFibonacci = 1;

System.out.println(firstFibonacci);

System.out.println(secondFibonacci);


for (int i = 2; i < n; i++) {

int currentFibonacci = firstFibonacci + secondFibonacci;

System.out.println(currentFibonacci);

firstFibonacci = secondFibonacci;

secondFibonacci = currentFibonacci;

}

}

}

 ========================================
import java.util.Scanner;

public class RecursiveFibonacci {
    int fib(int n) {
        if (n <= 1) {
            return n;
        }
        return fib(n - 1) + fib(n - 2);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of Fibonacci numbers to generate:");
        int n = sc.nextInt();
        sc.close();

        RecursiveFibonacci obj = new RecursiveFibonacci();
        System.out.println("The Fibonacci series:");

        for (int i = 0; i < n; i++) {
            System.out.print(obj.fib(i) + " ");
        }
    }
}

 ====================================
import java.util.Scanner;

public class ReverseNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any number:");
        int n = sc.nextInt();
        sc.close();

        int reversed = reverseNumber(n);

        System.out.println("The reverse number is: " + reversed);
    }

    private static int reverseNumber(int n) {
        int reversed = 0;
        while (n > 0) {
            reversed = reversed * 10 + n % 10;
            n /= 10;
        }
        return reversed;
    }
}

 ====================================
import java.util.Scanner;

public class PalindromeNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any number:");
        int n = sc.nextInt();
        sc.close();

        int k = n; // Store the original number
        int reversed = reverseNumber(n);

        System.out.println("The reverse number is: " + reversed);
        if (k == reversed) {
            System.out.println("Palindrome");
        } else {
            System.out.println("Not a palindrome");
        }
    }

    private static int reverseNumber(int n) {
        int reversed = 0;
        while (n > 0) {
            reversed = reversed * 10 + n % 10;
            n /= 10;
        }
        return reversed;
    }
}
scenario 2:
import java.util.Scanner;

public class PalindromeOrNot {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any number:");
        int n = sc.nextInt();
        sc.close();

        if (isPalindrome(n)) {
            System.out.println("Palindrome");
        } else {
            System.out.println("Not a palindrome");
        }
    }

    private static boolean isPalindrome(int n) {
        int original = n;
        int reversed = reverseNumber(n);
        return original == reversed;
    }

    private static int reverseNumber(int n) {
        int reversed = 0;
        while (n > 0) {
            reversed = reversed * 10 + n % 10;
            n /= 10;
        }
        return reversed;
    }
}
==============================
import java.util.Scanner;

public class LargestPalindromeInString {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string:");
        String input = sc.nextLine();
        sc.close();

        String largestPalindrome = findLargestPalindrome(input);
        System.out.println("The largest palindrome in the string is: " + largestPalindrome);
    }

    // Method to find the largest palindrome
    private static String findLargestPalindrome(String str) {
        String largestPalindrome = "";

        for (int i = 0; i < str.length(); i++) {
            // Odd-length palindromes
            String oddPalindrome = expandAroundCenter(str, i, i);
            if (oddPalindrome.length() > largestPalindrome.length()) {
                largestPalindrome = oddPalindrome;
            }

            // Even-length palindromes
            String evenPalindrome = expandAroundCenter(str, i, i + 1);
            if (evenPalindrome.length() > largestPalindrome.length()) {
                largestPalindrome = evenPalindrome;
            }
        }

        return largestPalindrome;
    }

    // Helper method to expand around center and check for palindrome
    private static String expandAroundCenter(String str, int left, int right) {
        while (left >= 0 && right < str.length() && str.charAt(left) == str.charAt(right)) {
            left--;
            right++;
        }
        return str.substring(left + 1, right);
    }
}
  ================================

import java.util.Scanner;


public class PrimeOrNot {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter one number:");

int n = sc.nextInt();

sc.close();


boolean isPrime = isPrime(n);


if (isPrime) {

System.out.println("The number is prime");

} else {

System.out.println("The number is not prime");

}

}


private static boolean isPrime(int n) {

if (n <= 1) {

return false;

}

for (int i = 2; i <= Math.sqrt(n); i++) {

if (n % i == 0) {

return false;

}

}

return true;

}

}

 =================================
import java.util.Scanner;

public class FindPrime {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter one number:");
        int n = sc.nextInt();
        sc.close();

        int count = 0;
        for (int i = 2; i <= n; i++) {
            if (isPrime(i)) {
                System.out.println(i);
                count++;
            }
        }

        System.out.println("The number of prime numbers: " + count);
    }

    private static boolean isPrime(int num) {
        if (num <= 1) {
            return false;
        }
        if (num <= 3) {
            return true;
        }
        if (num % 2 == 0 || num % 3 == 0) {
            return false;
        }
        for (int i = 5; i * i <= num; i += 6) {
            if (num % i == 0 || num % (i + 2) == 0) {
                return false;
            }
        }
        return true;
    }
}

 ================================

import java.util.Scanner;


public class PrintNumbers {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter one number:");

int n = sc.nextInt();

sc.close();


System.out.println("Numbers from 1 to " + n + ":");

for (int i = 1; i <= n; i++) {

System.out.println(i);

}

}

}

 =====================================

import java.util.Scanner;


public class StarPattern1 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of rows:");

int n = sc.nextInt();

sc.close();


System.out.println("Pattern:");

for (int i = 0; i <= n; i++) {

for (int j = 0; j <= i; j++) {

System.out.print(j);

}

System.out.println();

}

}

}

 ======================================

import java.util.Scanner;


public class StarPattern2 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter any number:");

int n = sc.nextInt();

sc.close();


System.out.println("Pattern:");

for (int i = n; i >= 0; i--) {

for (int j = 0; j <= i; j++) {

System.out.print(j);

}

System.out.println();

}

}

}

=====================================
import java.util.Scanner;

public class LinearSearch {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // Example array
        int[] array = {2, 4, 0, 1, 9};

        System.out.print("Enter the target value to search: ");
        int target = input.nextInt();

        // Perform linear search
        int result = linearSearch(array, target);

        if (result == -1) {
            System.out.println("Element not present in the array.");
        } else {
            System.out.println("Element found at index: " + result);
        }
    }

    public static int linearSearch(int[] array, int target) {
        for (int i = 0; i < array.length; i++) {
            if (array[i] == target) {
                return i;  // Return the index of the found element
            }
        }
        return -1;  // Element not found
    }
}
=========================================
import java.util.Scanner;

public class BinarySearch {
    public static void main(String[] args) {
        // Example sorted array
        int[] array = {2, 3, 4, 10, 40};
        
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the target value to search: ");
        int target = input.nextInt();
        input.close();

        // Perform binary search
        int result = binarySearch(array, target);
        
        if (result == -1) {
            System.out.println("Element not present in the array.");
        } else {
            System.out.println("Element found at index: " + result);
        }
    }

    // Binary search method
    public static int binarySearch(int[] array, int target) {
        int low = 0;
        int high = array.length - 1;

        while (low <= high) {
            // Avoids overflow compared to (low + high) / 2
            int mid = low + (high - low) / 2;  

            // Check if the target is present at mid
            if (array[mid] == target) {
                return mid;
            }

            // If target is greater, ignore the left half
            if (array[mid] < target) {
                low = mid + 1;
            } else {
                // If target is smaller, ignore the right half
                high = mid - 1;
            }
        }

        // Target was not present in the array
        return -1;
    }
}

===========================================

import java.util.Arrays;

import java.util.Scanner;


public class MergeSort {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);


// Read the size of the array

System.out.print("Enter the number of elements in the array: ");

int n = input.nextInt();


// Initialize the array

int[] array = new int[n];


// Read the elements of the array

System.out.println("Enter the elements of the array:");

for (int i = 0; i < n; i++) {

array[i] = input.nextInt();

}

input.close();


// Display the given array

System.out.println("Given Array: " + Arrays.toString(array));


// Perform merge sort

mergeSort(array, 0, array.length - 1);


// Display the sorted array

System.out.println("Sorted Array: " + Arrays.toString(array));

}


public static void mergeSort(int[] array, int left, int right) {

if (left < right) {

int mid = left + (right - left) / 2;


// Sort first and second halves

mergeSort(array, left, mid);

mergeSort(array, mid + 1, right);


// Merge the sorted halves

merge(array, left, mid, right);

}

}


public static void merge(int[] array, int left, int mid, int right) {

int n1 = mid - left + 1;

int n2 = right - mid;


// Create temp arrays

int[] leftArray = new int[n1];

int[] rightArray = new int[n2];


// Copy data to temp arrays

System.arraycopy(array, left, leftArray, 0, n1);

System.arraycopy(array, mid + 1, rightArray, 0, n2);


// Merge the temp arrays

int i = 0, j = 0;

int k = left;

while (i < n1 && j < n2) {

if (leftArray[i] <= rightArray[j]) {

array[k] = leftArray[i];

i++;

} else {

array[k] = rightArray[j];

j++;

}

k++;

}


// Copy remaining elements of leftArray[] if any

while (i < n1) {

array[k] = leftArray[i];

i++;

k++;

}


// Copy remaining elements of rightArray[] if any

while (j < n2) {

array[k] = rightArray[j];

j++;

k++;

}

}

}

==============================
import java.util.Arrays;
import java.util.Scanner;

public class QuickSort {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // Read the size of the array
        System.out.print("Enter the number of elements in the array: ");
        int n = input.nextInt();

        // Initialize the array
        int[] array = new int[n];

        // Read the elements of the array
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < n; i++) {
            array[i] = input.nextInt();
        }
        input.close();

        // Display the given array
        System.out.println("Given Array: " + Arrays.toString(array));

        // Perform quick sort
        quickSort(array, 0, array.length - 1);

        // Display the sorted array
        System.out.println("Sorted Array: " + Arrays.toString(array));
    }

    public static void quickSort(int[] array, int low, int high) {
        if (low < high) {
            // pi is partitioning index, array[pi] is now at right place
            int pi = partition(array, low, high);

            // Recursively sort elements before and after partition
            quickSort(array, low, pi - 1);
            quickSort(array, pi + 1, high);
        }
    }

    public static int partition(int[] array, int low, int high) {
        int pivot = array[high];
        int i = (low - 1); // index of smaller element
        for (int j = low; j < high; j++) {
            // If current element is smaller than the pivot
            if (array[j] < pivot) {
                i++;
                // swap array[i] and array[j]
                int temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
        // swap array[i + 1] and array[high] (or pivot)
        int temp = array[i + 1];
        array[i + 1] = array[high];
        array[high] = temp;

        return i + 1;
    }
}

=========================================
import java.util.Scanner;

public class DecimalToBinary {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        System.out.print("Enter a decimal number: ");
        int num = input.nextInt();
        
        String binaryString = convertDecimalToBinary(num);
        System.out.println("Decimal to binary: " + binaryString);
    }
    
    public static String convertDecimalToBinary(int num) {
        if (num == 0) return "0";
        
        StringBuilder binary = new StringBuilder();
        while (num > 0) {
            int remainder = num % 2;
            binary.insert(0, remainder);
            num = num / 2;
        }
        return binary.toString();
    }
}

---------------------------

No comments:

Post a Comment