Could you please help me with comments on the following code explaining how they work, I would like to better understand how the different operators work.
//Suma de los dígitos de un número natural
public static int sumDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
//Cantidad de dígitos de un número natural
public static int quantityDigits(int num) {
int quantity = 0;
while (num > 0) {
quantity++;
num /= 10;
}
return quantity;
}
//Cantidad de dígitos diferentes de un número natural
public static int differentsDigits(int num) {
int quantity = 0;
String differentsDigits = "";
do {
String digit = "" + (num % 10);
if (differentsDigits.indexOf(digit) == -1) {
quantity++;
differentsDigits += digit;
}
num /= 10;
} while (num > 0);
return quantity;
}
//Dígito máximo de un número natural
public static int maxDigit(int num) {
int max = 1;
while (num > 0) {
int remainder = num % 10;
if (remainder > max) {
max = remainder;
}
num /= 10;
}
return max;
}
//Determinar si el número es palíndromo
public static void palindromeNumber(int num) {
int n = num;
int reverse = 0, remainder;
while (num > 0) {
remainder = num % 10;
reverse = reverse * 10 + remainder;
num /=10;
}
if (reverse == n)
View.input("The number is palindrome.");
else
View.input("The number isn't palindrome.");
}
//Determinar si el número es primo
public static void primeNumber(int num) {
boolean prime = true;
if (num < 2)
prime = false;
else {
for (int i = 2; i*i <= num; i++) {
if ((num % i) == 0) {
prime = false;
break;
}
}
}
if (prime)
View.input("The number is prime.");
else
View.input("The number isn't prime.");
}
//Obtener los divisores primos de un número natural
public static void dividers(int num) {
for (int i = 2; i <= num; i++) {
if ((num % i) == 0) {
boolean simple = true;
for (int j = 2; j <= i/2; j++) {
if ((i % j) == 0) {
simple = false;
break;
}
}
if (simple)
System.out.printf("%d ", i);
}
}
}
//Obtener el máximo común divisor de dos números naturales
public static int gcd(int a, int b) {
while (b > 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
//Obtener el mínimo común múltiplo de dos números naturales
public static int lcm(int a, int b) {
return a * (b / gcd(a,b));
}
Thanks in advance.
Hello, I put comments in your code:
I have not commented on each line since the operations and the ways of programming are repeated.
Java