forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberPersistence.java
More file actions
79 lines (73 loc) · 2.57 KB
/
NumberPersistence.java
File metadata and controls
79 lines (73 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.thealgorithms.maths;
/**
* A utility class for calculating the persistence of a number.
*
* <p>This class provides methods to calculate:
* <ul>
* <li>Multiplicative persistence: The number of steps required to reduce a number to a single digit by multiplying its digits.</li>
* <li>Additive persistence: The number of steps required to reduce a number to a single digit by summing its digits.</li>
* </ul>
*
* <p>This class is final and cannot be instantiated.
*
* @see <a href="https://en.wikipedia.org/wiki/Persistence_of_a_number">Wikipedia: Persistence of a number</a>
*/
public final class NumberPersistence {
// Private constructor to prevent instantiation
private NumberPersistence() {
}
/**
* Calculates the multiplicative persistence of a given number.
*
* <p>Multiplicative persistence is the number of steps required to reduce a number to a single digit
* by multiplying its digits repeatedly.
*
* @param num the number to calculate persistence for; must be non-negative
* @return the multiplicative persistence of the number
* @throws IllegalArgumentException if the input number is negative
*/
public static int multiplicativePersistence(int num) {
if (num < 0) {
throw new IllegalArgumentException("multiplicativePersistence() does not accept negative values");
}
int steps = 0;
while (num >= 10) {
int product = 1;
int temp = num;
while (temp > 0) {
product *= temp % 10;
temp /= 10;
}
num = product;
steps++;
}
return steps;
}
/**
* Calculates the additive persistence of a given number.
*
* <p>Additive persistence is the number of steps required to reduce a number to a single digit
* by summing its digits repeatedly.
*
* @param num the number to calculate persistence for; must be non-negative
* @return the additive persistence of the number
* @throws IllegalArgumentException if the input number is negative
*/
public static int additivePersistence(int num) {
if (num < 0) {
throw new IllegalArgumentException("additivePersistence() does not accept negative values");
}
int steps = 0;
while (num >= 10) {
int sum = 0;
int temp = num;
while (temp > 0) {
sum += temp % 10;
temp /= 10;
}
num = sum;
steps++;
}
return steps;
}
}