0% found this document useful (0 votes)
14 views48 pages

Document (2

The document outlines algorithms and Java programs to check for various types of numbers: Keith numbers, Vampire numbers, Fascinating numbers, Hamming numbers, and Bouncy numbers. Each section includes a detailed algorithm followed by the corresponding Java code, along with variable descriptions and input-output examples. The programs utilize user input to determine and display whether the given number meets the criteria for each specific type.

Uploaded by

lakshyakeshari22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views48 pages

Document (2

The document outlines algorithms and Java programs to check for various types of numbers: Keith numbers, Vampire numbers, Fascinating numbers, Hamming numbers, and Bouncy numbers. Each section includes a detailed algorithm followed by the corresponding Java code, along with variable descriptions and input-output examples. The programs utilize user input to determine and display whether the given number meets the criteria for each specific type.

Uploaded by

lakshyakeshari22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Question - 1 : Write a program to check if a number is a

Keith number.

Algorithm
Step 1 - Start: Read the input number .
Step 2 - Extract Digits: Convert into its individual digits and store them
in an array digits.
Step 3 - Determine Length: Calculate the number of digits, , in .
STEP 4 - Initialize Sequence: Create a list or array sequence containing
the digits of .
Step 5 - Set Sum: Compute the initial sum of the digits and store it in
current_sum.
Step 6 - Start Loop: Begin a loop to generate new numbers in the
Fibonacci-like sequence.
Step 7 - Update Sum: In each iteration, calculate the sum of the last
numbers in the sequence.
Step 8 - Add to Sequence: Append the computed sum (current_sum) to
the sequence.
Step 9 – Check for Equality: If current_sum equals , is a Keith number.
Step 10 - Check for Exit: If current_sum exceeds , exit the loop, as is
not a Keith number.
Step 11 - Print Result: Based on the loop outcome, print whether is a
Keith number or not.
Step 12 - End: Stop the program or repeat for another input.
Program

import java.util.Scanner;
public class KeithNumber {

// Method to check if a number is a Keith number


public static boolean isKeithNumber(int n) {
// Convert the number into its digits
String numStr = Integer.toString(n);
int numDigits = numStr.length();
int[] digits = new int[numDigits];

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


digits[i] = Character.getNumericValue(numStr.charAt(i));
}

// Initialize a Fibonacci-like sequence


int[] sequence = new int[1000]; // Arbitrary large size
System.arraycopy(digits, 0, sequence, 0, numDigits);

int index = numDigits;


// Generate sequence until the sum exceeds or equals the input
number
while (true) {
int sum = 0;
for (int i = index - numDigits; i < index; i++) {
sum += sequence[i];
}

if (sum == n) {
return true; // It's a Keith number
} else if (sum > n) {
return false; // Not a Keith number
}

sequence[index] = sum;
index++;
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
// Input: Get the number to check
System.out.print("Enter a number to check if it's a Keith number:
");
int number = scanner.nextInt();

// Check and display result


if (isKeithNumber(number)) {
System.out.println(number + " is a Keith number.");
} else {
System.out.println(number + " is not a Keith number.");
}

scanner.close();
}
}
Variable Description

Variable Data – Type Description

n Integer Input a number to


check whether it is a
keith number

digits Integer - Array Array storing the


digits of n

sequence Integer - Array Fibonacci -like


sequence generated
from digits

current_sum Integer Sum of the last d


digits in the sequence

d Integer Number of digits in n


Input – Output

1. Input: 197
Output: 197 is a Keith number.

2. Input: 123
Output: 123 is not a Keith number.
Question – 2 : Write a program to check if a number is a
Vampire number and generate a list of all Vampire numbers
within a given range.
Algorithm
Step 1 - Initialize: Start the program and define necessary variables.
Step 2 - Input Range: Accept the range or specific number to check for
vampire numbers.
Step 3 - Validate Input: Ensure the input number has an even number of
digits (only even-digit numbers can be vampire numbers).
Step 4 - Generate Pairs: Split the number into two halves, generating all
possible permutations of its digits.
Step 5 - Form Products: Multiply each pair of permutations.
Step 6 - Check Length: Ensure the product has the same number of
digits as the original number.
Step 7 - Check Uniqueness: Confirm the digits of the product match the
original number's digits (without repetition or omission).
Step 8 - Exclude Trivial Cases: Avoid cases where trailing zeros result in
invalid pairs.
Step 9 - Store Vampire Numbers: Store numbers that meet all
conditions.
Step 10 - Output Vampire Numbers: Display the list of vampire numbers
in the given range.
Step 11 - Edge Case Handling: Handle invalid input or ranges without
vampire numbers.
Program

import java.util.*;
public class VampireNumbers {

// Function to check if a number is a vampire number


public static boolean isVampire(int num) {
String numStr = String.valueOf(num);
int len = numStr.length();

if (len % 2 != 0) return false; // Only even-length numbers can be


vampire numbers

int halfLen = len / 2;


char[] digits = numStr.toCharArray();
Arrays.sort(digits);

// Generate all permutations of the digits


List<String> permutations = generatePermutations(new
String(digits));
for (String perm : permutations) {
String left = perm.substring(0, halfLen);
String right = perm.substring(halfLen);

// Avoid trivial cases with leading zeros


if (left.startsWith("0") || right.startsWith("0")) continue;

int leftNum = Integer.parseInt(left);


int rightNum = Integer.parseInt(right);

if (leftNum * rightNum == num) {


return true;
}
}
return false;
}

// Function to generate all permutations of a string


public static List<String> generatePermutations(String str) {
List<String> permutations = new ArrayList<>();
permute(str.toCharArray(), 0, permutations);
return permutations;
}
private static void permute(char[] arr, int index, List<String>
permutations) {
if (index == arr.length - 1) {
permutations.add(new String(arr));
return;
}

for (int i = index; i < arr.length; i++) {


swap(arr, index, i);
permute(arr, index + 1, permutations);
swap(arr, index, i); // Backtrack
}
}

private static void swap(char[] arr, int i, int j) {


char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

// Main method
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the range (start and end): ");


int start = scanner.nextInt();
int end = scanner.nextInt();

System.out.println("Vampire Numbers in the range:");


for (int i = start; i <= end; i++) {
if (isVampire(i)) {
System.out.println(i);
}
}

scanner.close();
}
}
Variable Description

Variable Data – Type Description

num Integer The number being


checked for vampire
number properties

numStr Integer - Array String representation


of the number

len Integer - Array Length of the number


in digits

halfLen Integer Half the length of the


number’s digits

digits Integer Array of the number’s


digits

permutations List to store all


permutations of the
digits
left, right Substrings
representing two parts
of the number

leftNum, rightNum Integer representation


of left and right

start, end Range inputs provided


by the user

Input – Output

Input:
Enter the range (start and end):
1000 2000

Output:
Vampire Numbers in the range:
1260
1395
1435
1530
Question - 3 : Write a program to determine if a given
number is a Fascinating Number.

Algorithm
Step 1 - Start.
Step 2 - Read the integer input number.
Step 3 - Check if the number is less than 100:
 If yes, print "Not a Fascinating Number" and exit.
Step 4 - Compute doubleValue = number × 2.
Step 5 - Compute tripleValue = number × 3.
Step 6 - Concatenate the original number, doubleValue, and tripleValue
into a single string concatenated.
Step 7 - Verify that the length of concatenated is 9:
 If not, print "Not a Fascinating Number" and exit.
Step 8 - Initialize a loop to check digits from '1' to '9'.
 For each digit, check if it occurs exactly once in concatenated.
Step 9 - If any digit from '1' to '9' is missing or occurs more than once,
print "Not a Fascinating Number" and exit.
Step 10 - If all checks pass, print "Fascinating Number".
Step 11 - End.
Program

import java.util.Scanner;
public class FascinatingNumber {
public static boolean isFascinating(int number) {
if (number < 100) {
return false; // Fascinating numbers must be at least 3 digits long
}

// Compute double and triple values


int doubleValue = number * 2;
int tripleValue = number * 3;

// Concatenate the numbers into a single string


String concatenated = number + "" + doubleValue + "" +
tripleValue;

// Ensure the concatenated string is exactly 9 characters long


if (concatenated.length() != 9) {
return false;
}
// Check for each digit from '1' to '9'
for (char digit = '1'; digit <= '9'; digit++) {
int count = 0;
for (char c : concatenated.toCharArray()) {
if (c == digit) {
count++;
}
}
if (count != 1) {
return false; // Either digit is missing or occurs more than once
}
}

return true;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read the number from the user


System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Check and display if it's a fascinating number
if (isFascinating(number)) {
System.out.println(number + " is a Fascinating Number.");
} else {
System.out.println(number + " is not a Fascinating Number.");
}

scanner.close();
}
}
Variable Description

Variable Data – Type Description

number Integer The input number


entered by the user.

doubleValue Integer The result of


multiplying number
by 2.

tripleValue Integer The result of


multiplying number
by 3.

concatenated String The concatenated


string of number,
doubleValue, and
tripleValue.

digit Char Represent s digits


from 1 – to ‘9 during
the check

Tracks occurrences of
count a specific digit in
concatenated.

Input - Output

Example 1:
Input:
Enter a number: 192
Output:
192 is a Fascinating Number.

Example 2:
Input:
Enter a number: 853
Output:
853 is not a Fascinating Number.
Question - 4 : Write a Java program to determine whether a
given number is a Hamming Number.

Algorithm
Step 1 - Start.
Step 2 - Read the integer input number.
Step 3 - If number <= 0, print "Invalid input, number must be positive"
and exit.
Step 4 - If number == 1, print "1 is a Hamming Number" and exit (1 is
the smallest Hamming number).
Step 5 - Initialize a temporary variable temp = number.
Step 6 - Divide temp by 2 as long as it is divisible by 2.
Step 7 - Divide temp by 3 as long as it is divisible by 3.
Step 8 - Divide temp by 5 as long as it is divisible by 5.
Step 9 - After performing divisions, check the value of temp:
 If temp == 1, the original number is a Hamming Number.
 Otherwise, it is not a Hamming Number.
Step 10 - Print "Hamming Number" if the condition is satisfied.
Step 11 - Otherwise, print "Not a Hamming Number."
Step 12 - End the program.

Program
import java.util.Scanner;
public class HammingNumber {
public static boolean isHamming(int number) {
if (number <= 0) {
return false; // Hamming numbers are positive
}

// Divide by 2, 3, and 5 repeatedly


while (number % 2 == 0) {
number /= 2;
}
while (number % 3 == 0) {
number /= 3;
}
while (number % 5 == 0) {
number /= 5;
}

// If the result is 1, it's a Hamming Number


return number == 1;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Read input number


System.out.print("Enter a number: ");
int number = scanner.nextInt();

// Check and display if the number is a Hamming Number


if (isHamming(number)) {
System.out.println(number + " is a Hamming Number.");
} else {
System.out.println(number + " is not a Hamming Number.");
}

scanner.close();
}
}

Variable Description
Variable Data – Type Description

number Integer The input number


entered by the user.

temp Integer Temporary variable


used to repeatedly
divide number.

Input - Output

Example 1:
Enter a number: 12
Output:
12 is a Hamming Number.

Example 2:
Enter a number: 14
Output:
14 is not a Hamming Number.
Question - 5 : Write a Java program to determine whether a
given number is a Bouncy Number.

Algorithm
Step 1 - Start.
Step 2 - Read the integer input number.
Step 3 - If number < 100, print "Not a Bouncy Number" and exit
(numbers less than 100 are not bouncy).
Step 4 - Initialize two boolean variables: isIncreasing = true and
isDecreasing = true.
Step 5 - Convert the number into a string or an array of digits for digit-
wise comparison.
Step 6 - Initialize a loop to iterate through the digits of the number.
Step 7 - Compare each digit with the next digit:
 If the current digit is greater than the next digit, set isIncreasing =
false.
 If the current digit is less than the next digit, set isDecreasing =
false.
Step 8 - If both isIncreasing and isDecreasing remain true, the number is
not bouncy.
Step 9 - If either isIncreasing or isDecreasing is false but not both, the
number is also not bouncy.
Step 10 - If both isIncreasing and isDecreasing are false, the number is
bouncy.
Step 11 - Print "Bouncy Number" if the conditions in Step 10 are
satisfied.
Step 12 - Print "Not a Bouncy Number" otherwise.
Step 13 - End.

Program

import java.util.Scanner;
public class BouncyNumber {
public static boolean isBouncy(int number) {
if (number < 100) {
return false; // Numbers less than 100 are not bouncy
}

boolean isIncreasing = true;


boolean isDecreasing = true;

int lastDigit = number % 10; // Get the last digit


number /= 10; // Remove the last digit
while (number > 0) {
int currentDigit = number % 10; // Get the next digit
if (currentDigit < lastDigit) {
isIncreasing = false; // Not increasing
}
if (currentDigit > lastDigit) {
isDecreasing = false; // Not decreasing
}

lastDigit = currentDigit; // Update last digit


number /= 10; // Remove the digit
}

return !(isIncreasing || isDecreasing); // Bouncy if neither increasing


nor decreasing
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read input number


System.out.print("Enter a number: ");
int number = scanner.nextInt();

// Check and display if the number is a Bouncy Number


if (isBouncy(number)) {
System.out.println(number + " is a Bouncy Number.");
} else {
System.out.println(number + " is not a Bouncy Number.");
}

scanner.close();
}
}
Variable Description

Variable Data – Type Description

number Integer The input number


entered by the user.

isIncreasing Boolean Tracks whether the


number’s digits are in
non-decreasing order.

isDecreasing Boolean Tracks whether the


number’s digits are in
non-increasing order.

lastDigit Integer Stores the last digit of


the current number for
comparison.

currentDigit Integer Stores the digit being


compared with
lastDigit
Input - Output

Example 1:
Enter a number: 132
Output:
132 is a Bouncy Number.

Example 2:
Enter a number: 123
Output:
123 is not a Bouncy Number.
Question - 6 : Write a program to declare a matrix A[][] of
order (m*n) where ‘m’ is the number of rows and ‘n’ is the
number of columns such that both m and n must be greater than
2 and less than 10. Allow the user to input integers into this
matrix. Display appropriate error message for an invalid input.
Perform the following tasks on the matrix:
a) Display the input matrix
b) Rotate the matrix by 270 degrees anti clock wise and
display the resultant matrix.

Algorithm

Step 1 - Start.
Step 2 - Declare variables m, n, and a 2D matrix AL of size m x n.
Step 3 - Prompt the user to enter the number of rows m and columns n
of the matrix.
Step 4 - If m or n is less than or equal to 2 or greater than or equal to 10,
print an error message and exit.
Step 5 - Create a 2D matrix AL of size m x n.
Step 6 - Prompt the user to input integers into the matrix AL.
Step 7 - Store the user inputs into the matrix AL.
Step 8 - Display the matrix AL.
Step 9 - Rotate the matrix by 270 degrees anti-clockwise.
 To rotate 270 degrees anti-clockwise, the element at position (i, j)
in the original matrix should move to position (j, m-1-i) in the
rotated matrix.
Step 10 - Display the rotated matrix after the 270-degree rotation.
Step 12 - End.

Program

import java.util.Scanner;
public class MatrixRotation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input number of rows and columns


System.out.print("Enter the number of rows (m): ");
int m = scanner.nextInt();
System.out.print("Enter the number of columns (n): ");
int n = scanner.nextInt();

// Validate input
if (m <= 2 || m >= 10 || n <= 2 || n >= 10) {
System.out.println("Error: Both the number of rows and columns
must be greater than 2 and less than 10.");
return;
}

// Create the matrix


int[][] A[][] = new int[m][n];

// Input elements into the matrix


System.out.println("Enter elements of the matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
AL[i][j] = scanner.nextInt();
}
}

// Display the input matrix


System.out.println("\nInput Matrix:");
displayMatrix(A[][], m, n);

// Rotate the matrix by 270 degrees anti-clockwise


int[][] rotated = rotateMatrix270(A[][], m, n);
// Display the rotated matrix
System.out.println("\nRotated Matrix (270 degrees anti-
clockwise):");
displayMatrix(rotated, n, m); // Note: the rotated matrix will have
dimensions n x m
}

// Method to display the matrix


public static void displayMatrix(int[][] matrix, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}

// Method to rotate the matrix 270 degrees anti-clockwise


public static int[][] rotateMatrix270(int[][] matrix, int m, int n) {
int[][] rotated = new int[n][m]; // Rotated matrix dimensions are n x
m
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
rotated[j][m - 1 - i] = matrix[i][j];
}
}
return rotated;
}
}

Variable Description

Variable Data – Type Description

n Integer Represents the


number of rows in the
input matrix.

m Integer Represents the


number of columns in
the input matrix.
A[][] Integer A two-dimensional
array (matrix) to store
the input matrix
elements provided by
the user.

rotated Integer A two-dimensional


array (matrix) that
stores the result of the
270-degree anti-
clockwise rotation.

matrix Integer A parameter in


methods display
Matrix and
rotateMatrix2 70,
representing a 2D
matrix.

rows Integer A parameter in the


display Matrix
method, representing
the number of rows of
the matrix

cols Integer A parameter in the


display Matrix
method, representing
the number of
columns of the matrix.
Input - Output

Example 1:
Input
Enter the number of rows (m): 3
Enter the number of columns (n): 3
Enter elements of the matrix:
123
456
789

Output
Input Matrix:
123
456
789

Rotated Matrix (270 degrees anti-clockwise):


369
258
147

Example 2:
Input
Enter the number of rows (m): 1
Enter the number of columns (n): 3

Output
Error: Both the number of rows and columns must be greater than 2 and
less than 10.
Question - 7 : Write a program to declare a square matrix
arr[ ][ ] of order n. Check if the matrix is Doubly Markov matrix
or not.

Algorithm
Step 1 : Start.
Step 2 : Define the size of the square matrix n.
Step 3 : Declare a square matrix arr[][] of order n.
Step 4 : Input elements into the matrix arr[][].
Step 5 : Initialize a boolean flag isDoublyMarkov = true.
Step 6 : Check if all rows are probability vectors:
 For each row, ensure that all elements are between 0 and 1.
 Ensure the sum of all elements in the row is equal to 1.
 If any row fails the above conditions, set isDoublyMarkov = false
and break.
Step 7 : If rows satisfy the probability condition, proceed to check
columns.
Step 8 : Check if all columns are probability vectors:
 For each column, ensure that all elements are between 0 and 1.
 Ensure the sum of all elements in the column is equal to 1.
 If any column fails the above conditions, set isDoublyMarkov =
false and break.
Step 9 : If both row and column conditions are satisfied, the matrix is a
Doubly Markov matrix.
Step 10 : Else, the matrix is not a Doubly Markov matrix.
Step 11 : Output the result of whether the matrix is Doubly Markov or
not.
Step 12 : End

Program

import java.util.Scanner;
public class DoublyMarkovMatrix {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Step 2: Input size of the matrix


System.out.print("Enter the size of the square matrix (n): ");
int n = scanner.nextInt();

// Step 3: Declare the square matrix


double[][] arr = new double[n][n];

// Step 4: Input elements into the matrix


System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = scanner.nextDouble();
}
}

// Step 5: Initialize isDoublyMarkov flag


boolean isDoublyMarkov = true;

// Step 6-7: Check rows


for (int i = 0; i < n; i++) {
double rowSum = 0;
for (int j = 0; j < n; j++) {
if (arr[i][j] < 0 || arr[i][j] > 1) {
isDoublyMarkov = false;
break;
}
rowSum += arr[i][j];
}
if (Math.abs(rowSum - 1) > 1e-9) {
isDoublyMarkov = false;
break;
}
}

// Step 8-9: Check columns (only if rows are valid)


if (isDoublyMarkov) {
for (int j = 0; j < n; j++) {
double colSum = 0;
for (int i = 0; i < n; i++) {
if (arr[i][j] < 0 || arr[i][j] > 1) {
isDoublyMarkov = false;
break;
}
colSum += arr[i][j];
}
if (Math.abs(colSum - 1) > 1e-9) {
isDoublyMarkov = false;
break;
}
}
}

// Step 10-11: Output result


if (isDoublyMarkov) {
System.out.println("The matrix is a Doubly Markov matrix.");
} else {
System.out.println("The matrix is NOT a Doubly Markov
matrix.");
}

// Step 12: End


scanner.close();
}
}
Variable Description

Variable Data – Type Description

n Integer Size of the square


matrix

temp Double The square matrix of


size n x n containing
elements as input.

isDoublyMarkov Boolean A flag to indicate


whether the matrix is
a Doubly Markov
matrix (true/ false).
Input - Output

Example 1 :
Input :
Enter the size of the square matrix (n): 2
Enter the elements of the matrix:
0.5 0.6
0.4 0.3

Output :
The matrix is NOT a Doubly Markov matrix

Example 2 :
Input :
Enter the size of the square matrix (n): 3
Enter the elements of the matrix:
0.4 0.4 0.2
0.3 0.5 0.3
0.3 0.1 0.5

Output :
The matrix is NOT a Doubly Markov matrix.
Question – 8 : Write a program to declare a square matrix
arr[ ][ ] of order n. Check if the matrix is Doubly Markov matrix
or not.

Algorithm
Step – 1: Start the algorithm.
Step – 2: Create the main method and store the size of the square matrix
entered by the user in n.
Step – 3: Create a double dimension array arr[][] of size n*n.
Step – 4: Declare 3 integer variables as x, a and b and initialize them as
1, 0 and n-1 respectively.
Step – 5: Start a while loop till a < n.
(A) Create a for loop where control variable of the loop I varies
from a to b where I increases by 1 for every iteration. Store the
value of x in arr[i][a] and increment the value of x by 1. Close
the for loop. Increment the value of a by 1.
(B) Create another for loop where control variable of the loop I
varies from a to b where I increases by 1 for every iteration.
Store the value of x in arr[b][i] and increment the value of x by
1. Close the for loop.
(C) Create another for loop where control variable of the loop I
varies from b to a where I decreases by 1 for every iteration.
Store the value of x in arr[a-1][i] and increment the value of x
by 1. Close the for loop. Close the while loop.
Step – 6: Print the array.
Step – 7: End the algorithm.

Program

Input: n = 5

Output:

Circular Matrix Anti-Clockwise:

1 16 15 14 13

2 17 24 23 12
3 18 25 22 11

4 19 20 21 10

5 6 7 8 9

Input: n = 3

Output:

Circular Matrix Anti-Clockwise:

1 8 7

2 9 6

3 4 5

You might also like