Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
49 views

Basic Programs

The document contains Java code examples for various mathematical and numerical algorithms, including calculating factorials, checking for prime numbers, finding the greatest common divisor and least common multiple of two numbers, calculating the nth Fibonacci number, reversing a number, checking for palindromes, calculating square roots using Newton's method, exponentiation, summing digits of a number, determining even/oddness, finding the largest digit, and counting the digits.

Uploaded by

IG Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Basic Programs

The document contains Java code examples for various mathematical and numerical algorithms, including calculating factorials, checking for prime numbers, finding the greatest common divisor and least common multiple of two numbers, calculating the nth Fibonacci number, reversing a number, checking for palindromes, calculating square roots using Newton's method, exponentiation, summing digits of a number, determining even/oddness, finding the largest digit, and counting the digits.

Uploaded by

IG Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Here's a Java program to find the factorial of a number:

import java.util.Scanner;

public class Factorial {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

long factorial = 1;

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

factorial *= i;

System.out.println("The factorial of " + number + " is: " + factorial);

Here's a Java program to check if a number is prime:

import java.util.Scanner;

public class PrimeCheck {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

boolean isPrime = true;

if (number <= 1) {
isPrime = false;

} else {

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

if (number % i == 0) {

isPrime = false;

break;

if (isPrime) {

System.out.println(number + " is a prime number.");

} else {

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

Here's a Java program to find the greatest common divisor (GCD) of two numbers:

import java.util.Scanner;

public class GCD {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number: ");

int number1 = scanner.nextInt();

System.out.print("Enter the second number: ");

int number2 = scanner.nextInt();

int gcd = findGCD(number1, number2);


System.out.println("The GCD of " + number1 + " and " + number2 + " is: " + gcd);

public static int findGCD(int a, int b) {

if (b == 0) {

return a;

return findGCD(b, a % b);

Here's a Java program to calculate the least common multiple (LCM) of two numbers:

import java.util.Scanner;

public class LCM {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number: ");

int number1 = scanner.nextInt();

System.out.print("Enter the second number: ");

int number2 = scanner.nextInt();

int lcm = findLCM(number1, number2);

System.out.println("The LCM of " + number1 + " and " + number2 + " is: " + lcm);

public static int findLCM(int a, int b) {

return (a * b) / findGCD(a, b);

}
public static int findGCD(int a, int b) {

if (b == 0) {

return a;

return findGCD(b, a % b);

Here's a Java program to find the nth Fibonacci number:

import java.util.Scanner;

public class Fibonacci {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the value of n: ");

int n = scanner.nextInt();

long fibN = findNthFibonacci(n);

System.out.println("The " + n + "th Fibonacci number is: " + fibN);

public static long findNthFibonacci(int n) {

if (n <= 0) {

return -1; // Invalid input

} else if (n == 1 || n == 2) {

return 1;

} else {

long fibNMinus2 = 1;
long fibNMinus1 = 1;

long fibN = 0;

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

fibN = fibNMinus1 + fibNMinus2;

fibNMinus2 = fibNMinus1;

fibNMinus1 = fibN;

return fibN;

Here's a Java program to reverse a number:

import java.util.Scanner;

public class ReverseNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

int reversedNumber = reverse(number);

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

public static int reverse(int number) {

int reversedNumber = 0;

while (number != 0) {
int digit = number % 10;

reversedNumber = reversedNumber * 10 + digit;

number /= 10;

return reversedNumber;

Here's a Java program to check if a number is a palindrome:

import java.util.Scanner;

public class PalindromeCheck {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

if (isPalindrome(number)) {

System.out.println(number + " is a palindrome.");

} else {

System.out.println(number + " is not a palindrome.");

public static boolean isPalindrome(int number) {

int originalNumber = number;

int reversedNumber = 0;

while (number > 0) {

int digit = number % 10;

reversedNumber = reversedNumber * 10 + digit;


number /= 10;

return originalNumber == reversedNumber;

Java program to calculate the square root of a number without using built-in functions. We will use
the Newton-Raphson method for approximating the square root:

import java.util.Scanner;

public class SquareRoot {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

double number = scanner.nextDouble();

if (number < 0) {

System.out.println("Cannot calculate the square root of a negative number.");

} else {

double squareRoot = calculateSquareRoot(number);

System.out.println("The square root of " + number + " is approximately: " + squareRoot);

public static double calculateSquareRoot(double number) {

double guess = number / 2.0; // Start with an initial guess

double epsilon = 1e-15; // A small value for precision

while (Math.abs(guess * guess - number) > epsilon) {

guess = (guess + number / guess) / 2.0; // Use the Newton-Raphson formula

}
return guess;

Here's a Java program to implement a function to raise a number to a power (a^b):

import java.util.Scanner;

public class Power {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the base (a): ");

double base = scanner.nextDouble();

System.out.print("Enter the exponent (b): ");

int exponent = scanner.nextInt();

double result = power(base, exponent);

System.out.println(base + " raised to the power of " + exponent + " is: " + result);

public static double power(double base, int exponent) {

if (exponent == 0) {

return 1.0;

double result = 1.0;

for (int i = 1; i <= Math.abs(exponent); i++) {

result *= base;

}
if (exponent < 0) {

return 1.0 / result; // If the exponent is negative, return the reciprocal

} else {

return result;

Here's a Java program to compute the sum of digits in a number:

import java.util.Scanner;

public class SumOfDigits {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

int sum = sumOfDigits(number);

System.out.println("The sum of digits in " + number + " is: " + sum);

public static int sumOfDigits(int number) {

int sum = 0;

while (number != 0) {

int digit = number % 10;

sum += digit;
number /= 10;

return sum;

Here's a Java program to determine if a number is even or odd:

import java.util.Scanner;

public class EvenOddCheck {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

if (isEven(number)) {

System.out.println(number + " is an even number.");

} else {

System.out.println(number + " is an odd number.");

public static boolean isEven(int number) {

return number % 2 == 0;

}
Here's a Java program to find the largest digit in a number:

import java.util.Scanner;

public class LargestDigit {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

int largestDigit = findLargestDigit(number);

System.out.println("The largest digit in " + number + " is: " + largestDigit);

public static int findLargestDigit(int number) {

int largestDigit = 0;

while (number > 0) {

int digit = number % 10;

largestDigit = Math.max(largestDigit, digit);

number /= 10;

return largestDigit;

}}
Here's a Java program to count the number of digits in a given number:

import java.util.Scanner;

public class CountDigits {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

long number = scanner.nextLong();

int digitCount = countDigits(number);

System.out.println("The number of digits in " + number + " is: " + digitCount);

public static int countDigits(long number) {

// Convert the number to a positive value if it's negative

number = Math.abs(number);

if (number == 0) {

return 1; // 0 has one digit

int count = 0;

while (number > 0) {

number /= 10;
count++;

return count;

Here's a Java program to convert a decimal number to binary:

import java.util.Scanner;

public class DecimalToBinary {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a decimal number: ");

int decimalNumber = scanner.nextInt();

String binaryNumber = convertToBinary(decimalNumber);

System.out.println("Binary representation: " + binaryNumber);

public static String convertToBinary(int decimalNumber) {

if (decimalNumber == 0) {

return "0"; // Special case for zero

}
StringBuilder binary = new StringBuilder();

while (decimalNumber > 0) {

int remainder = decimalNumber % 2;

binary.insert(0, remainder); // Prepend the remainder to the binary representation

decimalNumber /= 2;

return binary.toString();

Here's a Java program to convert a binary number to a decimal number:

import java.util.Scanner;

public class BinaryToDecimal {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a binary number: ");

String binaryNumber = scanner.nextLine();

int decimalNumber = convertToDecimal(binaryNumber);

System.out.println("Decimal representation: " + decimalNumber);

}
public static int convertToDecimal(String binaryNumber) {

int decimalNumber = 0;

int length = binaryNumber.length();

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

char digit = binaryNumber.charAt(i);

if (digit == '1') {

// Add the corresponding power of 2 to the decimal number

decimalNumber += Math.pow(2, length - 1 - i);

return decimalNumber;

Here's a Java program to convert a decimal number to Roman numerals:

import java.util.Scanner;

public class DecimalToRoman {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a decimal number: ");

int decimalNumber = scanner.nextInt();

if (decimalNumber >= 1 && decimalNumber <= 3999) {


String romanNumeral = convertToRoman(decimalNumber);

System.out.println("Roman numeral representation: " + romanNumeral);

} else {

System.out.println("The number is out of the valid range for Roman numerals.");

public static String convertToRoman(int decimalNumber) {

String[] romanNumerals = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX",
"V", "IV", "I"};

int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

StringBuilder roman = new StringBuilder();

int i = 0;

while (decimalNumber > 0) {

if (decimalNumber - values[i] >= 0) {

roman.append(romanNumerals[i]);

decimalNumber -= values[i];

} else {

i++;

return roman.toString();

}}
Here's a Java program to find the first N prime numbers:

import java.util.Scanner;

public class PrimeNumbers {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the value of N: ");

int N = scanner.nextInt();

if (N > 0) {

int[] primeNumbers = generatePrimes(N);

System.out.println("The first " + N + " prime numbers are:");

for (int prime : primeNumbers) {

System.out.print(prime + " ");

} else {

System.out.println("Invalid input. N should be a positive integer.");

public static int[] generatePrimes(int N) {

int[] primes = new int[N];

int count = 0;

int number = 2;
while (count < N) {

if (isPrime(number)) {

primes[count] = number;

count++;

number++;

return primes;

public static boolean isPrime(int number) {

if (number <= 1) {

return false;

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

if (number % i == 0) {

return false;

return true;

}
Here's a Java program to check if a number is an Armstrong number:

import java.util.Scanner;

public class ArmstrongNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

if (isArmstrongNumber(number)) {

System.out.println(number + " is an Armstrong number.");

} else {

System.out.println(number + " is not an Armstrong number.");

public static boolean isArmstrongNumber(int number) {

int originalNumber, remainder, result = 0;

int n = 0;

originalNumber = number;

// Count the number of digits in the number

while (originalNumber != 0) {

originalNumber /= 10;
n++;

originalNumber = number;

// Calculate the Armstrong number

while (originalNumber != 0) {

remainder = originalNumber % 10;

result += Math.pow(remainder, n);

originalNumber /= 10;

return result == number;

Here's a Java program to generate a list of prime numbers up to N using the Sieve of
Eratosthenes algorithm:

import java.util.Scanner;

import java.util.Arrays;

public class SieveOfEratosthenes {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number (N): ");

int N = scanner.nextInt();
if (N >= 2) {

boolean[] isPrime = new boolean[N + 1];

Arrays.fill(isPrime, true);

isPrime[0] = isPrime[1] = false;

// Apply the Sieve of Eratosthenes algorithm

for (int p = 2; p * p <= N; p++) {

if (isPrime[p]) {

for (int i = p * p; i <= N; i += p) {

isPrime[i] = false;

System.out.println("Prime numbers up to " + N + " are:");

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

if (isPrime[i]) {

System.out.print(i + " ");

} else {

System.out.println("There are no prime numbers for N < 2.");

}
Here's a Java program to calculate the sum of all multiples of a given number within a
range:

import java.util.Scanner;

public class SumOfMultiples {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a range (from): ");

int from = scanner.nextInt();

System.out.print("Enter a range (to): ");

int to = scanner.nextInt();

System.out.print("Enter the multiple: ");

int multiple = scanner.nextInt();

int sum = sumMultiplesInRange(from, to, multiple);

System.out.println("The sum of multiples of " + multiple + " in the range " + from + " to
" + to + " is: " + sum);

public static int sumMultiplesInRange(int from, int to, int multiple) {

int sum = 0;

for (int i = from; i <= to; i++) {

if (i % multiple == 0) {

sum += i;

}
}

return sum;

Here's a Java program to determine if a number is a perfect number:

import java.util.Scanner;

public class PerfectNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

if (isPerfectNumber(number)) {

System.out.println(number + " is a perfect number.");

} else {

System.out.println(number + " is not a perfect number.");

public static boolean isPerfectNumber(int number) {

if (number <= 1) {

return false; // Perfect numbers are positive integers greater than 1.

}
int sumOfDivisors = 1; // 1 is always a divisor.

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

if (number % i == 0) {

sumOfDivisors += i;

if (i != (number / i)) {

sumOfDivisors += (number / i);

return sumOfDivisors == number;

Here's a Java program to check if a number is a palindrome in a different base, such as


binary:

import java.util.Scanner;

public class PalindromeInBase {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

System.out.print("Enter the base (e.g., 2 for binary): ");

int base = scanner.nextInt();


if (isPalindromeInBase(number, base)) {

System.out.println(number + " is a palindrome in base " + base + ".");

} else {

System.out.println(number + " is not a palindrome in base " + base + ".");

public static boolean isPalindromeInBase(int number, int base) {

if (number < 0) {

return false; // Negative numbers are not palindromes.

String numberInBase = Integer.toString(number, base);

return isPalindrome(numberInBase);

public static boolean isPalindrome(String str) {

int left = 0;

int right = str.length() - 1;

while (left < right) {

if (str.charAt(left) != str.charAt(right)) {

return false;

left++;
right--;

return true;

Here's a Java program to find the nth term of an arithmetic progression:

import java.util.Scanner;

public class ArithmeticProgression {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first term (a): ");

double a = scanner.nextDouble();

System.out.print("Enter the common difference (d): ");

double d = scanner.nextDouble();

System.out.print("Enter the value of n: ");

int n = scanner.nextInt();

double nthTerm = calculateNthTerm(a, d, n);

System.out.println("The " + n + "th term of the arithmetic progression is: " + nthTerm);

public static double calculateNthTerm(double a, double d, int n) {


return a + (n - 1) * d;

Here's a Java program to find the nth term of a geometric progression:

import java.util.Scanner;

public class GeometricProgression {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first term (a): ");

double a = scanner.nextDouble();

System.out.print("Enter the common ratio (r): ");

double r = scanner.nextDouble();

System.out.print("Enter the value of n: ");

int n = scanner.nextInt();

double nthTerm = calculateNthTerm(a, r, n);

System.out.println("The " + n + "th term of the geometric progression is: " + nthTerm);

public static double calculateNthTerm(double a, double r, int n) {

return a * Math.pow(r, n - 1);

}
Here's a Java program to check if a number is a happy number:

import java.util.HashSet;

import java.util.Scanner;

import java.util.Set;

public class HappyNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

if (isHappyNumber(number)) {

System.out.println(number + " is a happy number.");

} else {

System.out.println(number + " is not a happy number.");

public static boolean isHappyNumber(int number) {

Set<Integer> seen = new HashSet<>();

while (number != 1 && !seen.contains(number)) {

seen.add(number);

int sum = 0;

while (number > 0) {


int digit = number % 10;

sum += digit * digit;

number /= 10;

number = sum;

return number == 1;

Here's a Java program to calculate the square of a number using bitwise operators:

import java.util.Scanner;

public class SquareUsingBitwise {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

long square = calculateSquare(number);

System.out.println("The square of " + number + " is: " + square);

public static long calculateSquare(int number) {


if (number < 0) {

return -1; // Handling negative numbers

if (number == 0) {

return 0;

if (number == 1) {

return 1;

// Calculate the square using bitwise operators

int x = number;

int y = number;

long result = 0;

while (y > 0) {

if ((y & 1) != 0) {

result = result + x;

x <<= 1;

y >>= 1;

}
return result;

Here's a Java program to check if a number is a narcissistic number:

import java.util.Scanner;

public class NarcissisticNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

if (isNarcissisticNumber(number)) {

System.out.println(number + " is a narcissistic number.");

} else {

System.out.println(number + " is not a narcissistic number.");

public static boolean isNarcissisticNumber(int number) {

int originalNumber = number;

int n = countDigits(number);

int sum = 0;

while (number > 0) {


int digit = number % 10;

sum += Math.pow(digit, n);

number /= 10;

return sum == originalNumber;

public static int countDigits(int number) {

int count = 0;

while (number > 0) {

number /= 10;

count++;

return count;

Here's a Java program to find the digital root of a number:

import java.util.Scanner;

public class DigitalRoot {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();


int root = findDigitalRoot(number);

System.out.println("The digital root of " + number + " is: " + root);

public static int findDigitalRoot(int number) {

// Repeatedly sum the digits of the number until a single-digit result is obtained.

while (number >= 10) {

int sum = 0;

while (number > 0) {

sum += number % 10;

number /= 10;

number = sum;

return number;

Here's a Java program to determine if a number is a strong number:

import java.util.Scanner;

public class StrongNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


System.out.print("Enter a number: ");

int number = scanner.nextInt();

if (isStrongNumber(number)) {

System.out.println(number + " is a strong number.");

} else {

System.out.println(number + " is not a strong number.");

public static boolean isStrongNumber(int number) {

int originalNumber = number;

int sumOfFactorialDigits = 0;

while (number > 0) {

int digit = number % 10;

sumOfFactorialDigits += factorial(digit);

number /= 10;

return sumOfFactorialDigits == originalNumber;

public static int factorial(int n) {

if (n == 0) {
return 1;

int fact = 1;

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

fact *= i;

return fact;

Here's a Java program to calculate the sum of proper divisors of a number:

import java.util.Scanner;

public class SumOfDivisors {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

int sum = sumOfProperDivisors(number);

System.out.println("The sum of proper divisors of " + number + " is: " + sum);

public static int sumOfProperDivisors(int number) {


int sum = 0;

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

if (number % i == 0) {

sum += i;

return sum;

Here's a Java program to find the number of trailing zeros in the factorial of a number:

import java.util.Scanner;

public class TrailingZerosInFactorial {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

int trailingZeros = countTrailingZerosInFactorial(number);

System.out.println("The number of trailing zeros in " + number + "! is: " +


trailingZeros);

}
public static int countTrailingZerosInFactorial(int number) {

int trailingZeros = 0;

// Divide the number by increasing powers of 5 and add the quotient to the trailingZeros

for (int i = 5; number / i >= 1; i *= 5) {

trailingZeros += number / i;

return trailingZeros;

Here's a Java program to check if a number is a perfect square:

import java.util.Scanner;

public class PerfectSquare {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

if (isPerfectSquare(number)) {

System.out.println(number + " is a perfect square.");

} else {

System.out.println(number + " is not a perfect square.");

}
}

public static boolean isPerfectSquare(int number) {

if (number < 0) {

return false; // Negative numbers are not perfect squares.

int sqrt = (int) Math.sqrt(number);

return sqrt * sqrt == number;

Here's a Java program to calculate the binary representation of a number without


leading zeros:

import java.util.Scanner;

public class BinaryWithoutLeadingZeros {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a decimal number: ");

int decimalNumber = scanner.nextInt();

String binaryNumber = convertToBinary(decimalNumber);

System.out.println("Binary representation without leading zeros: " + binaryNumber);

}
public static String convertToBinary(int decimalNumber) {

if (decimalNumber == 0) {

return "0"; // Special case for zero

StringBuilder binary = new StringBuilder();

boolean leadingZeros = true;

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

int bit = (decimalNumber >> i) & 1;

if (bit == 1) {

leadingZeros = false;

if (!leadingZeros) {

binary.append(bit);

return binary.toString();

Here's a Java program to determine the number of digits needed to represent a number
in a given base:

import java.util.Scanner;
public class NumberOfDigitsInBase {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

System.out.print("Enter the base: ");

int base = scanner.nextInt();

int digits = countDigitsInBase(number, base);

System.out.println("The number of digits needed to represent " + number + " in base " +
base + " is: " + digits);

public static int countDigitsInBase(int number, int base) {

if (number == 0) {

return 1; // Zero has one digit in any base.

int digits = 0;

while (number > 0) {

number /= base;

digits++;

}
return digits;

Here's a Java program to generate the nth Gray code:

import java.util.Scanner;

public class GrayCode {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the value of N: ");

int N = scanner.nextInt();

if (N >= 0) {

int grayCode = generateGrayCode(N);

System.out.println("The " + N + "th Gray code is: " + grayCode);

} else {

System.out.println("Invalid input. N should be a non-negative integer.");

public static int generateGrayCode(int N) {

// Gray code is generated by XOR-ing N with (N >> 1)

return N ^ (N >> 1);

}
Here's a Java program to find the sum of two binary numbers:

import java.util.Scanner;

public class SumBinaryNumbers {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first binary number: ");

String binary1 = scanner.next();

System.out.print("Enter the second binary number: ");

String binary2 = scanner.next();

String sum = addBinaryNumbers(binary1, binary2);

System.out.println("The sum of " + binary1 + " and " + binary2 + " is: " + sum);

public static String addBinaryNumbers(String binary1, String binary2) {

int carry = 0;

StringBuilder sum = new StringBuilder();

int i = binary1.length() - 1;

int j = binary2.length() - 1;

while (i >= 0 || j >= 0 || carry > 0) {

int bit1 = i >= 0 ? binary1.charAt(i--) - '0' : 0;

int bit2 = j >= 0 ? binary2.charAt(j--) - '0' : 0;


int currentSum = bit1 + bit2 + carry;

sum.insert(0, currentSum % 2);

carry = currentSum / 2;

return sum.toString();

Here's a Java program to calculate the square of a large number using a fast
exponentiation algorithm:

import java.util.Scanner;

public class FastExponentiation {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the base (a): ");

long base = scanner.nextLong();

System.out.print("Enter the exponent (b): ");

long exponent = scanner.nextLong();

long result = fastExponentiation(base, exponent);

System.out.println(base + " raised to the power " + exponent + " is: " + result);

public static long fastExponentiation(long base, long exponent) {


if (exponent == 0) {

return 1;

long result = 1;

while (exponent > 0) {

if (exponent % 2 == 1) {

result *= base;

base *= base;

exponent /= 2;

return result;

Here's a Java program to determine if a number is a power of 2:

import java.util.Scanner;

public class PowerOfTwo {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

if (isPowerOfTwo(number)) {
System.out.println(number + " is a power of 2.");

} else {

System.out.println(number + " is not a power of 2.");

public static boolean isPowerOfTwo(int number) {

// A power of two has only one bit set in its binary representation.

// For example, 4 (binary 100) or 8 (binary 1000).

// So, to check if a number is a power of two, we can use the bitwise AND operation.

// If (number & (number - 1)) is 0, it's a power of two.

return (number > 0) && ((number & (number - 1)) == 0);

Here's a Java program to check if a number is a Fibonacci number:

import java.util.Scanner;

public class FibonacciNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

if (isFibonacci(number)) {
System.out.println(number + " is a Fibonacci number.");

} else {

System.println(number + " is not a Fibonacci number.");

public static boolean isPerfectSquare(int x) {

int s = (int) Math.sqrt(x);

return s * s == x;

public static boolean isFibonacci(int number) {

// A number is a Fibonacci number if and only if one of 5*x*x + 4 or 5*x*x - 4 is a


perfect square.

return isPerfectSquare(5 * number * number + 4) || isPerfectSquare(5 * number *


number - 4);

Here's a Java program to calculate the product of two large numbers using the
Karatsuba algorithm:

import java.util.Scanner;

public class KaratsubaMultiplication {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number: ");

String num1 = scanner.next();


System.out.print("Enter the second number: ");

String num2 = scanner.next();

String product = karatsubaMultiply(num1, num2);

System.out.println("The product of " + num1 + " and " + num2 + " is: " + product);

public static String karatsubaMultiply(String num1, String num2) {

int len1 = num1.length();

int len2 = num2.length();

// If one of the numbers is 0, return "0"

if (len1 == 1 && num1.charAt(0) == '0' || len2 == 1 && num2.charAt(0) == '0') {

return "0";

// If one of the numbers is 1, return the other number

if (len1 == 1 && num1.charAt(0) == '1') {

return num2;

if (len2 == 1 && num2.charAt(0) == '1') {

return num1;

}
// Pad the numbers to have the same length

int maxLength = Math.max(len1, len2);

if (len1 < maxLength) {

num1 = "0".repeat(maxLength - len1) + num1;

if (len2 < maxLength) {

num2 = "0".repeat(maxLength - len2) + num2;

// Divide the numbers into halves

int split = maxLength / 2;

String a = num1.substring(0, split);

String b = num1.substring(split);

String c = num2.substring(0, split);

String d = num2.substring(split);

// Recursively calculate the products

String ac = karatsubaMultiply(a, c);

String bd = karatsubaMultiply(b, d);

String ad_bc = karatsubaMultiply(add(a, b), add(c, d));

// Calculate the result using the Karatsuba formula

String product = subtract(subtract(add(ac + "0".repeat(maxLength), ad_bc), ac), bd);

return product;
}

public static String add(String num1, String num2) {

// Pad both numbers to the same length

int maxLength = Math.max(num1.length(), num2.length());

if (num1.length() < maxLength) {

num1 = "0".repeat(maxLength - num1.length()) + num1;

if (num2.length() < maxLength) {

num2 = "0".repeat(maxLength - num2.length()) + num2;

StringBuilder result = new StringBuilder();

int carry = 0;

for (int i = maxLength - 1; i >= 0; i--) {

int digit1 = num1.charAt(i) - '0';

int digit2 = num2.charAt(i) - '0';

int sum = digit1 + digit2 + carry;

carry = sum / 10;

result.insert(0, sum % 10);

if (carry > 0) {
result.insert(0, carry);

return result.toString();

public static String subtract(String num1, String num2) {

// Pad both numbers to the same length

int maxLength = Math.max(num1.length(), num2.length());

if (num1.length() < maxLength) {

num1 = "0".repeat(maxLength - num1.length()) + num1;

if (num2.length() < maxLength) {

num2 = "0".repeat(maxLength - num2.length()) + num2;

StringBuilder result = new StringBuilder();

int borrow = 0;

for (int i = maxLength - 1; i >= 0; i--) {

int digit1 = num1.charAt(i) - '0';

int digit2 = num2.charAt(i) - '0';

int diff = digit1 - digit2 - borrow;

if (diff < 0) {
diff += 10;

borrow = 1;

} else {

borrow = 0;

result.insert(0, diff);

return result.toString().replaceFirst("^0+(?!$)", "");

Here's a Java program to find the nth triangular number:

import java.util.Scanner;

public class TriangularNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the value of N: ");

int N = scanner.nextInt();

int triangular = calculateTriangularNumber(N);

System.out.println("The " + N + "th triangular number is: " + triangular);

}
public static int calculateTriangularNumber(int N) {

// The nth triangular number is the sum of the first N natural numbers.

return (N * (N + 1)) / 2;

Here's a Java program to generate a list of prime factors of a number:

import java.util.Scanner;

public class PrimeFactors {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

System.out.println("Prime factors of " + number + " are: ");

listPrimeFactors(number);

public static void listPrimeFactors(int number) {

// Start with the smallest prime factor, which is 2.

while (number % 2 == 0) {

System.out.print("2 ");

number /= 2;

}
// Continue with odd prime factors from 3 onwards.

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

while (number % i == 0) {

System.out.print(i + " ");

number /= i;

// If the remaining number is greater than 2, it is a prime factor.

if (number > 2) {

System.out.print(number);

Here's a Java program to calculate the harmonic mean of a list of numbers:

import java.util.Scanner;

public class HarmonicMean {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int n = scanner.nextInt();
if (n <= 0) {

System.out.println("Please enter a valid number of elements.");

return;

double[] numbers = new double[n];

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

System.out.print("Enter number " + (i + 1) + ": ");

numbers[i] = scanner.nextDouble();

double harmonicMean = calculateHarmonicMean(numbers);

System.out.println("The harmonic mean of the numbers is: " + harmonicMean);

public static double calculateHarmonicMean(double[] numbers) {

double sumOfReciprocals = 0.0;

for (double number : numbers) {

if (number == 0) {

// Harmonic mean is undefined if any number is zero.

return 0.0;

}
sumOfReciprocals += 1 / number;

return numbers.length / sumOfReciprocals;

Here's a Java program to determine if a number is abundant:

import java.util.Scanner;

public class AbundantNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

if (isAbundant(number)) {

System.out.println(number + " is an abundant number.");

} else {

System.out.println(number + " is not an abundant number.");

public static boolean isAbundant(int number) {

if (number <= 1) {

return false; // Abundant numbers are defined for positive integers greater than 1.
}

int sumOfDivisors = 1; // Initialize with 1 as all numbers are divisible by 1.

for (int i = 2; i * i <= number; i++) {

if (number % i == 0) {

sumOfDivisors += i;

if (i != number / i) {

sumOfDivisors += number / i;

return sumOfDivisors > number;

Here's a Java program to check if a number is a strobogrammatic number:

import java.util.Scanner;

public class StrobogrammaticNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

String number = scanner.nextLine();


if (isStrobogrammatic(number)) {

System.out.println(number + " is a strobogrammatic number.");

} else {

System.out.println(number + " is not a strobogrammatic number.");

public static boolean isStrobogrammatic(String number) {

int left = 0;

int right = number.length() - 1;

while (left <= right) {

char leftChar = number.charAt(left);

char rightChar = number.charAt(right);

if (!isStrobogrammaticPair(leftChar, rightChar)) {

return false;

left++;

right--;

return true;

}
public static boolean isStrobogrammaticPair(char a, char b) {

return (a == '0' && b == '0') || (a == '1' && b == '1') || (a == '8' && b == '8') || (a == '6'
&& b == '9') || (a == '9' && b == '6');

Here's a Java program to find the intersection of two lists of numbers:

import java.util.ArrayList;

import java.util.Scanner;

import java.util.List;

public class IntersectionOfLists {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

List<Integer> list1 = new ArrayList<>();

List<Integer> list2 = new ArrayList<>();

System.out.println("Enter the first list of numbers. Enter -1 to finish.");

int num;

while (true) {

num = scanner.nextInt();

if (num == -1) {

break;

list1.add(num);

}
System.out.println("Enter the second list of numbers. Enter -1 to finish.");

while (true) {

num = scanner.nextInt();

if (num == -1) {

break;

list2.add(num);

List<Integer> intersection = findIntersection(list1, list2);

if (intersection.isEmpty()) {

System.out.println("There are no common elements in the two lists.");

} else {

System.out.print("The intersection of the two lists is: ");

for (int element : intersection) {

System.out.print(element + " ");

public static List<Integer> findIntersection(List<Integer> list1, List<Integer> list2) {

List<Integer> intersection = new ArrayList<>();


for (int element : list1) {

if (list2.contains(element) && !intersection.contains(element)) {

intersection.add(element);

return intersection;

Here's a Java program to determine the number of divisors of a number:

import java.util.Scanner;

public class NumberOfDivisors {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

int divisors = countDivisors(number);

System.out.println("The number of divisors of " + number + " is: " + divisors);

public static int countDivisors(int number) {

int count = 0;
for (int i = 1; i <= number; i++) {

if (number % i == 0) {

count++;

return count;

Here's a Java program to calculate the sum of cubes of the first N natural numbers:

import java.util.Scanner;

public class SumOfCubes {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a positive integer N: ");

int N = scanner.nextInt();

if (N < 1) {

System.out.println("Please enter a positive integer.");

return;

long sum = calculateSumOfCubes(N);


System.out.println("The sum of cubes of the first " + N + " natural numbers is: " + sum);

public static long calculateSumOfCubes(int N) {

long sum = 0;

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

sum += (long) Math.pow(i, 3);

return sum;

Here's a Java program to find the nth Catalan number:

import java.util.Scanner;

public class CatalanNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the value of N: ");

int N = scanner.nextInt();

long catalan = calculateCatalanNumber(N);


System.out.println("The " + N + "th Catalan number is: " + catalan);

public static long calculateCatalanNumber(int N) {

if (N <= 1) {

return 1;

long catalan = 0;

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

catalan += calculateCatalanNumber(i) * calculateCatalanNumber(N - i - 1);

return catalan;

You might also like