0% found this document useful (0 votes)
3 views29 pages

Computer One Shot

The document contains multiple Java classes that perform various tasks, including checking for Hamming numbers, calculating project submission dates, finding longest consecutive alphabetical substrings, evaluating quiz answers, determining the day of the week for a given date, rotating a matrix, and finding prime pairs that sum to a given even number. Each class includes methods for input, processing, and outputting results. The code demonstrates fundamental programming concepts such as loops, conditionals, and data structures.

Uploaded by

rruma3025
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)
3 views29 pages

Computer One Shot

The document contains multiple Java classes that perform various tasks, including checking for Hamming numbers, calculating project submission dates, finding longest consecutive alphabetical substrings, evaluating quiz answers, determining the day of the week for a given date, rotating a matrix, and finding prime pairs that sum to a given even number. Each class includes methods for input, processing, and outputting results. The code demonstrates fundamental programming concepts such as loops, conditionals, and data structures.

Uploaded by

rruma3025
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/ 29

import java.util.

Scanner;

// Class to check whether a number is a Hamming number

class hamming {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Input the number

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

int n = sc.nextInt();

// Check for negative input

if (n < 0) {

System.out.println("NEGATIVE NUMBER ENTERED.");

System.out.println("INVALID INPUT");

return;

int t = n; // Store original number

String f = ""; // To store prime factorization as a string

boolean first = true; // To manage '*' symbol placement in output

// Prime factorization

for (int i = 2; i <= t / i; i++) {

while (n % i == 0) {

if (!first) f += "*"; // Add '*' between factors

f += i; // Append the factor

n /= i; // Reduce number

first = false; // Set first to false after first factor

// If any prime factor remains after loop (greater than sqrt of t)

if (n > 1) {

if (!first) f += "*";

f += n;

}
// Display the factorized form

System.out.println(t + "=" + f);

// Split the factor string and check if all factors are 2, 3, or 5

boolean isHam = true;

String[] p = f.split("\\*");

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

int val = Integer.parseInt(p[i]);

if (val != 2 && val != 3 && val != 5) {

isHam = false;

break; // Exit if any factor is not 2, 3, or 5

// Display result

if (isHam)

System.out.println(t + " IS A HAMMING NUMBER");

else

System.out.println(t + " IS NOT A HAMMING NUMBER");

import java.util.*;

// Class to calculate project submission date

class projdate {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Input the project date and the day of the week

System.out.print("ENTER PROJECT DATE (dd/mm/yyyy): ");

String s = sc.nextLine();
System.out.print("DAY OF THE WEEK: ");

String d = sc.nextLine().toUpperCase(); // Not used in logic, but input

accepted

// Split the date string into day, month, and year

String[] parts = s.split("/");

if (parts.length != 3) {

System.out.println("INVALID DATE");

return; // Stop if date is in wrong format

// Parse day, month, and year as integers

int dd = Integer.parseInt(parts[0]);

int mm = Integer.parseInt(parts[1]);

int yy = Integer.parseInt(parts[2]);

// Validate if the entered date is a real calendar date

if (!isValid(dd, mm, yy)) {

System.out.println("INVALID DATE");

return;

// Create a Calendar object and set it to the project starting date

Calendar c = Calendar.getInstance();

c.set(yy, mm - 1, dd); // Note: months are 0-based in Calendar class

// Add 89 more days to get the submission date (starting day is

counted as Day 1)

c.add(Calendar.DATE, 89);

// Check if the final submission day is a Sunday

int finalDay = c.get(Calendar.DAY_OF_WEEK); // 1 = Sunday, 2 =

Monday, ..., 7 = Saturday

if (finalDay == Calendar.SUNDAY) {

c.add(Calendar.DATE, 1); // Add one more day if submission falls

on Sunday}

// Extract the final submission date (day, month, year)


int subd = c.get(Calendar.DATE);

int subm = c.get(Calendar.MONTH) + 1; // Add 1 because months are

0-based

int suby = c.get(Calendar.YEAR);

// Array to convert day index to day name

String[] days = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY",

"THURSDAY", "FRIDAY", "SATURDAY"};

String dayName = days[c.get(Calendar.DAY_OF_WEEK) - 1]; // Get day

name for final date

// Print the final project submission date and day

System.out.println("PROJECT SUBMISSION DATE: " + format(subd) +

"/" + format(subm) + "/" + suby);

System.out.println("DAY OF THE WEEK: " + dayName);

// Function to check if a given date is valid

static boolean isValid(int d, int m, int y) {

if (m < 1 || m > 12 || d < 1)

return false;

// Days in each month (non-leap year)

int[] md = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

// If leap year and February, set days to 29

if (m == 2 && isLeap(y))

md[1] = 29;

return d <= md[m - 1];

// Function to check if a year is a leap year

static boolean isLeap(int y) {

return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);

// Function to format day or month with leading zero (e.g., 1 -> 01)

static String format(int x) {


if (x < 10) return "0" + x;

return "" + x;

import java.util.*;

// Class to find the longest consecutive alphabetical substring from input

string

class Consecutive

String s; // Input string stored here

// Constructor initializes string to empty

Consecutive()

s = "";

// Method to take input from user

void input()

Scanner sc = new Scanner(System.in);

System.out.println("Enter a String in UPPERCASE");s = sc.nextLine();

// Validate input: length <= 50 and string is uppercase

// NOTE: Comparing strings with == is incorrect; use equals() or

equalsIgnoreCase()

if (!(s.length() <= 50 && s.equals(s.toUpperCase())))

System.out.println("INVALID SENTENCE");

System.exit(0);

// Main processing method to find longest consecutive letters substring


void process()

// Remove all spaces

s = s.replaceAll(" ", "");

// This loop intends to keep only one occurrence of each character,

// but modifying the string inside a loop causes logical errors.

// Consider using a LinkedHashSet or another method to keep order

without duplicates.

for (int i = 0; i < s.length(); i++)

char ch = s.charAt(i);

s = s.replaceAll(Character.toString(ch), "") + ch;

String ns = "";

// Build a string 'ns' of unique letters sorted alphabetically

for (int i = 65; i <= 90; i++) // ASCII A-Z

if (s.indexOf((char) i) >= 0)

ns = ns + (char) i;

String x = "", w = "";

int max = 0;

// Find the longest substring in ns where letters are consecutive

alphabets

for (int i = 0; i < ns.length() - 1; i++)

for (int j = i + 1; j <= ns.length(); j++)

w = ns.substring(i, j); if (check(w) && w.length() > max)


{

x = w;

max = w.length();

// Output results

if (x.length() > 1)

System.out.println(x);

else

System.out.println("NO CONSECUTIVE LETTERS PRESENT");

// Helper method to check if string characters are consecutive alphabets

boolean check(String z)

for (int i = 0; i < z.length() - 1; i++)

if (z.charAt(i) + 1 != z.charAt(i + 1))

return false;

return true;

// Main method to run the program

static void main()

Consecutive ob = new Consecutive();

ob.input();

ob.process();

}
}

import java.util.*;

// Class Quiz to store and evaluate quiz answers

public class Quiz

char a[][]; // 2D array to store answers of all participants

int n; // number of participants

char key[]; // array to store the answer key

// Constructor to initialize values

Quiz(int nn)

n = nn;

a = new char[n][5]; // each participant answers 5 questions

key = new char[5]; // answer key for 5 questions

// Method to take input from user

void input()

// Valid number of participants must be between 3 and 11

if (!(n >= 3 && n <= 11))

System.exit(0); // exits the program if condition fails

Scanner sc = new Scanner(System.in);

System.out.println("Q1 Q2 Q3 Q4 Q5");

// Input answers for each participant

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

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

for (int j = 0; j < 5; j++)


{

a[i][j] = sc.next().toUpperCase().charAt(0); // read one character

answer

// Input the answer key

System.out.print("Key : ");

for (int i = 0; i < 5; i++)

key[i] = sc.next().toUpperCase().charAt(0);

// Method to process answers and calculate scores

void process()

int c = 0; // score counter for each participant

int max = 0; // to keep track of highest score

int r = 0; // to store the participant number with highest score

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

// Calculate score for each participant

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

for (int j = 0; j < 5; j++)

if (a[i][j] == key[j]) // correct answer

c += 1;

System.out.println("PARTICIPANT " + (i + 1) + ": " + c);

// Check if this participant has the highest score so far


if (c > max)

max = c;

r = i + 1; // store participant number (1-based index)

}c = 0; // reset counter for next participant

System.out.println("Highest score: Participant " + r);

// Main method

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

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

Quiz ob = new Quiz(sc.nextInt()); // create Quiz object

ob.input(); // take input

ob.process(); // compute and display results

import java.util.*;

class DayFinder {

int day, month, year; // To store input date

String result; // To store the final day of the week or "Invalid Date"

void input() {

Scanner sc = new Scanner(System.in);

System.out.print("Enter date (dd mm yyyy): ");

day = sc.nextInt(); // Read day

month = sc.nextInt(); // Read month

year = sc.nextInt(); // Read year

}
void process() {

// Check for invalid year and month

if (year < 1900 || year > 2100 || month < 1 || month > 12) {

result = "Invalid Date";

return;

// Array for days in each month

int[] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

// Adjust for leap year

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

monthDays[1] = 29;

// Validate day

if (day < 1 || day > monthDays[month - 1]) {

result = "Invalid Date";

return;

int days = 0; // Total number of days since 1 Jan 1900

// Add days for full years passed

for (int y = 1900; y < year; y++)

days += ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) ? 366 : 365;

// Add days for full months of current year

for (int m = 1; m < month; m++)

days += monthDays[m - 1];

// Add days of current month

days += day - 1;

// Weekday calculation based on modulo 7 (since Jan 1, 1900 =

Monday)

String[] week = {"Monday", "Tuesday", "Wednesday", "Thursday",

"Friday", "Saturday", "Sunday"};

result = week[days % 7];

}
void display() {

// Output result

System.out.println("Day of the week: " + result);

}public static void main(String[] args) {

DayFinder d = new DayFinder(); // Create object

d.input(); // Read input

d.process(); // Process the date

d.display(); // Display result

import java.util.*;

class Rotation {

int m; // Matrix size (m x m)

int a[][]; // 2D array to hold the matrix

Rotation(int nn) {

m = nn; // Constructor to set matrix size

void input() {

// Check if size is valid

if (!(m > 2 && m < 10)) {

System.out.println("INVALID INPUT");

System.exit(0);

Scanner sc = new Scanner(System.in);

System.out.println("Enter the matrix of order " + m + "x" + m);

a = new int[m][m]; // Allocate memory for matrix

// Input matrix elements


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

for (int j = 0; j < m; j++)

a[i][j] = sc.nextInt();}

void tasks() {

System.out.println("original matrix");

display(); // Show original matrix

// Step 1: Transpose the matrix

int b[][] = new int[m][m];

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

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

b[j][i] = a[i][j];

// Step 2: Reverse each row of the transposed matrix

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

for (int j = 0; j < m / 2; j++) {

int t = b[i][j];

b[i][j] = b[i][m - j - 1];

b[i][m - j - 1] = t;

// Step 3: Replace original matrix with rotated one

a = b;

System.out.println("new matrix");

display(); // Display rotated matrix

// Step 4: Sum of corner elements

int s = a[0][0] + a[0][m - 1] + a[m - 1][0] + a[m - 1][m - 1];

System.out.println(s); // Output sum of corners

void display() {
// Display matrix elements

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

for (int j = 0; j < m; j++)

System.out.print(a[i][j] + "\t");

System.out.println();

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the value of m");

Rotation ob = new Rotation(sc.nextInt()); // Create object with given

sizeob.input(); // Input matrix

ob.tasks(); // Perform operations

import java.util.*;

class Goldbach {

int n; // Even number to be expressed as sum of two primes

Goldbach() {

n = 0; // Constructor initializes n to 0

void input() {

Scanner sc = new Scanner(System.in);

System.out.println("Enter an even integer");

n = sc.nextInt();

// Check for valid input: even, between 10 and 49

if (!(n > 9 && n < 50 && n % 2 == 0)) {

System.out.println("INVALID INPUT");

System.exit(0);

}
}

void process() {

System.out.println("PRIME PAIRS ARE: ");

// Iterate through all pairs (i, j) such that i + j == n

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

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

if (isPrime(i) && isPrime(j)) {

if (i + j == n) {

System.out.println(i + "," + j);

boolean isPrime(int x) {

int c = 0;

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

if (x % i == 0)

c += 1;

return c == 2; // Prime if only divisible by 1 and itself

static void main() {

Goldbach ob = new Goldbach(); // Create object

ob.input(); // Take input

ob.process(); // Show prime pairs that sum to n

}
import java.util.Scanner;

class Main {

int[] a; // 1D array to store integers

int[][] b; // 2D matrix to be filled based on the array

int n; // Size of the array and matrix

void input() {

Scanner sc = new Scanner(System.in);

// Accept n such that 3 ≤ n < 10

do {

System.out.print("Enter size N (3 to 9): ");

n = sc.nextInt();

} while (n <= 2 || n >= 10);

a = new int[n];

b = new int[n][n];

// Input only positive integers into array

System.out.println("Enter " + n + " positive integers:");

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

int val;

do {

val = sc.nextInt(); // Reject non-positive values

} while (val <= 0);

a[i] = val;

void sort() {

// Bubble sort the array in ascending order

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

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

if (a[j] > a[j + 1]) {

int t = a[j];

a[j] = a[j + 1];


a[j + 1] = t;

void fillMatrix() {

// Fill matrix rows based on sorted array

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

int k = 0;

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

if (i == 0) {

b[i][j] = a[j]; // First row = full array

} else {

if (j < n - i) {

b[i][j] = a[j]; // Left side of row

} else {

b[i][j] = a[k]; // Fill right with repeating values

k++;

void showArray() {

// Display sorted array

System.out.print("Sorted array: ");

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

System.out.print(a[i] + " ");

System.out.println();

}
void showMatrix() {

// Display filled matrix

System.out.println("Filled matrix:");

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

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

System.out.print(b[i][j] + "\t");

System.out.println();

public static void main(String[] args) {

Main obj = new Main();

obj.input(); // Step 1: Accept input

obj.sort(); // Step 2: Sort the array

obj.showArray(); // Step 3: Display the sorted array

obj.fillMatrix(); // Step 4: Fill the matrix

obj.showMatrix(); // Step 5: Display the matrix

import java.util.Scanner;

class ParagraphProcessor {

String para; // Input paragraph

String s1, s2; // Two sentences extracted from the paragraph

void input() {

Scanner sc = new Scanner(System.in);

System.out.println("Enter a paragraph with TWO sentences (in UPPER

CASE):");

para = sc.nextLine().trim(); // Remove leading/trailing spaces

}
boolean isValid() {

// Count sentence-ending punctuation marks to check if there are

exactly 2 sentences

int count = 0;

for (int i = 0; i < para.length(); i++) {char ch = para.charAt(i);

if (ch == '.' || ch == '?' || ch == '!') {

count++;

return count == 2;

void splitSentences() {

// Find the first punctuation mark to split the paragraph

int idx = -1;

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

char ch = para.charAt(i);

if (ch == '.' || ch == '?' || ch == '!') {

idx = i;

break;

s1 = para.substring(0, idx + 1).trim(); // First sentence

s2 = para.substring(idx + 1).trim(); // Second sentence

void findCommonWords() {

// Remove all characters except uppercase letters and spaces

String s1clean = s1.replaceAll("[^A-Z ]", "");

String s2clean = s2.replaceAll("[^A-Z ]", "");

String[] w1 = s1clean.split(" "); // Words from sentence 1

String[] w2 = s2clean.split(" "); // Words from sentence 2

// Find common words manually


String[] common = new String[Math.min(w1.length, w2.length)];

int c = 0;

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

for (int j = 0; j < w2.length; j++) {

if (w1[i].equals(w2[j]) && !isInArray(common, c, w1[i])) {

common[c++] = w1[i];

break;

System.out.println(s1);

System.out.println(s2);

if (c == 0) {

System.out.println("NO COMMON WORDS");return;

// Count frequency of each common word in both sentences

String[] allWords = (s1clean + " " + s2clean).split(" ");

System.out.println("COMMOM WORDS FREQUENCY");

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

int count = 0;

for (int j = 0; j < allWords.length; j++) {

if (common[i].equals(allWords[j])) {

count++;

System.out.println(common[i] + " " + count);

// Helper method to check if word is already in common words array

boolean isInArray(String[] arr, int size, String word) {

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


if (arr[i].equals(word)) {

return true;

return false;

public static void main(String[] args) {

ParagraphProcessor obj = new ParagraphProcessor();

obj.input();

if (!obj.isValid()) {

System.out.println("INVALID INPUT");

return;

obj.splitSentences();

obj.findCommonWords();

import java.util.Scanner;

public class PalindromeConverter {// Method to check if a word is a palindrome

public static boolean isPal(String w) {

return w.equals(new StringBuilder(w).reverse().toString());

// Method to convert a word to a palindrome by appending reverse of its

prefix

public static String toPal(String w) {

int i = w.length() - 1;

// Skip identical characters from the end

while (i > 0 && w.charAt(i) == w.charAt(i - 1)) i--;

// Append the reverse of the remaining prefix


return w + new StringBuilder(w.substring(0, i)).reverse().toString();

// Method to check whether the input sentence is valid

public static boolean isValid(String s) {

if (s.isEmpty()) return false;

char end = s.charAt(s.length() - 1);

// Sentence must end with '.', '?' or '!'

if (end != '.' && end != '?' && end != '!') return false;

String body = s.substring(0, s.length() - 1);

// No double spaces allowed

if (body.contains(" ")) return false;

// All characters in body must be uppercase letters or spaces

for (char c : body.toCharArray()) {

if (!(Character.isUpperCase(c) || c == ' ')) return false;

return true;

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Prompt user for input

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

String s = sc.nextLine().trim();

// Validate the sentence

if (!isValid(s)) {

System.out.println("INVALID INPUT");

return;

// Print the original valid sentence

System.out.println(s); char end = s.charAt(s.length() - 1); // Ending punctuation

String[] words = s.substring(0, s.length() - 1).split(" "); // Split into

words
StringBuilder out = new StringBuilder(); // For storing the result

// Process each word

for (String w : words) {

// If palindrome, keep as is; else convert to palindrome

out.append(isPal(w) ? w : toPal(w)).append(" ");

// Print final output sentence with punctuation

System.out.println(out.toString().trim() + end);

import java.util.Scanner;

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

class Keith {

private int num; // The original number

private int[] digits; // Array to store its digits

// Constructor to initialize the number and extract its digits

public Keith(int num) {

this.num = num;

this.digits = extractDigits(num);

// Method to extract digits from the number and return as an array

private int[] extractDigits(int n) {

int len = String.valueOf(n).length(); // Number of digits

int[] d = new int[len]; // Array to store digits

int i = len - 1;

while (n > 0) {

d[i--] = n % 10; // Extract digit from right

n /= 10;

return d;
}

// Method to check whether the number is a Keith number

public boolean isKeith() {

int n = digits.length; // Number of digits

int[] seq = new int[100]; // Array to generate the sequence (max size

assumed)

// Initialize the sequence with the digits of the number

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

seq[i] = digits[i];

int i = n;

int sum;

// Generate the sequence by summing previous n terms

while (true) {

sum = 0;

for (int j = i - n; j < i; j++) {

sum += seq[j];

if (sum == num) return true; // Number appears in sequence =>

Keith number

if (sum > num) break; // Surpassed the number => Not a Keith

number

seq[i++] = sum; // Add next term to sequence

return false;

// Getter to return the number

public int getNum() {

return num;

}
// Main class to run the program

public class KeithNumberCheck {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

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

int x = sc.nextInt();

// Validate the input

if (x <= 0) {

System.out.println("INVALID INPUT");

return;

// Create an object of class Keith and check

Keith k = new Keith(x);

if (k.isKeith()) {

System.out.println(x + " IS A KEITH NUMBER.");

} else {

System.out.println(x + " IS NOT A KEITH NUMBER.");

import java.util.Scanner;

class LuckyApp {

int n; // The initial size of the list (N)

int[] arr; // Array to hold the current list of numbers

int len; // Current length of the array after filtering

// Constructor initializes the array with numbers 1 to n

LuckyApp(int n) {

this.n = n;

arr = new int[n];

len = n;
init(); // Fill array with 1 to n

}// Initialize the array with numbers from 1 to n

void init() {

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

arr[i] = i + 1;

// Generate the Lucky numbers using the filtering steps

int[] get() {

int step = 2; // Starting step (remove every 2nd element)

// Continue filtering while step <= current length of the array

while (step <= len) {

int[] temp = new int[len]; // Temporary array to hold filtered values

int idx = 0; // Index for temp array

// Remove every 'step'th element from arr

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

// Keep element if (i+1) is NOT divisible by step

if ((i + 1) % step != 0) {

temp[idx++] = arr[i];

arr = temp; // Update arr to filtered array

len = idx; // Update current length after filtering

step++; // Increment step for next iteration

// Copy the resulting lucky numbers into a new array of correct size

int[] res = new int[len];

System.arraycopy(arr, 0, res, 0, len);

return res;

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

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

int x = sc.nextInt();

if (x <= 0) {

System.out.println("INVALID INPUT");

return;

LuckyApp lg = new LuckyApp(x); // Create LuckyApp object

int[] out = lg.get(); // Get lucky numbers// Print lucky numbers less than input x

System.out.print("The Lucky numbers less than " + x + " are: ");

for (int num : out) {

if (num < x) System.out.print(num + " ");

System.out.println();

import java.util.Scanner;

class Sphenic {

int n; // Number to be checked

int[] primes = new int[3]; // Array to store the 3 distinct prime factors

int count = 0; // To count the number of distinct prime factors found

// Constructor to initialize the number

Sphenic(int n) {

this.n = n;

// Method to check if a number is prime

boolean isPrime(int x) {

if (x < 2) return false; // Numbers less than 2 are not prime

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


if (x % i == 0) return false; // Not a prime if divisible by any i

return true; // Prime if no divisor found

// Method to check if the number is a Sphenic number

boolean check() {

int temp = n; // Copy of the number for manipulation

for (int i = 2; i <= temp && count < 3; i++) {

if (temp % i == 0 && isPrime(i)) {

int freq = 0; // To count how many times 'i' divides 'temp'

while (temp % i == 0) {

temp /= i;

freq++;

// If a prime factor repeats (i.e., exponent > 1), it's not Sphenic

if (freq > 1) return false;

// Store this distinct prime factor

primes[count++] = i;

// Valid Sphenic number must have exactly 3 distinct prime factors

and nothing left

return count == 3 && temp == 1;

// Method to print the result

void print() {

if (check()) {

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

System.out.println(n + "=" + primes[0] + " x " + primes[1] + " x " +

primes[2]);

} else {
System.out.println(n + " is not a Sphenic number");

// Main method to take input and execute the program

public static void main(String[] args) {

Scanner sc = new Scanner(System.in); // Scanner object for input

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

int x = sc.nextInt(); // Read input

if (x <= 0) {

System.out.println("INVALID INPUT"); // Handle non-positive

numbers

return;

Sphenic sp = new Sphenic(x); // Create object

sp.print(); // Call the print method

You might also like