Trisanjit Number
PROGRAM
import java.util.Scanner;
public class TrisanjitNumber {
public static int digitSum(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
public static int positionSum(int num) {
int sum = 0, position = 1;
while (num > 0) {
sum += (num % 10) * position;
num /= 10;
position++;
}
return sum;
}
public static int reverseNumber(int num) {
int reversed = 0;
while (num > 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
return reversed;
}
public static boolean isTrisanjitNumber(int num) {
int reversed = reverseNumber(num);
int digitCount = String.valueOf(num).length();
int sumDigits = digitSum(num);
int posSum = positionSum(reversed);
return sumDigits % 2 == 0 && posSum % digitCount == 0 && reversed % 3 == 0;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (isTrisanjitNumber(num)) {
System.out.println("The number " + num + " is a Trisanjit Number.");
} else {
System.out.println("The number " + num + " is NOT a Trisanjit Number.");
}
}
}
LOGIC
Reverse the number and calculate the digit sum:
Example: For the number 246, the reverse is 642.
The digit sum is calculated as 2+4+6=12. Since 12 is even, the first condition is satisfied.
Calculate the position sum of the reversed number:
Example: For the reversed number 642, calculate the position sum using:
(6×1)+(4×2)+(2×3)=6+8+6=20.Check the conditions:
The digit sum must be even: 12 (even). Condition met.
The position sum modulo the number of digits must be 0:
The number of digits in 246 is 3.
20mod3=0. Condition met.The reversed number must be divisible by 3:
642mod3=0. Condition met.
Final Result:
Since all conditions are satisfied, 246 is a Trisanjit Number.
SAMPLE INPUT/OUTPUT
Input: 132
Output: The number 132 is NOT a Trisanjit Number.
Input: 123
Output: The number 123 is NOT a Trisanjit Number.
Input: 246
Output: The number 246 is a Trisanjit Number.
Comments
Post a Comment