-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSingle.java
More file actions
45 lines (42 loc) · 1.23 KB
/
Single.java
File metadata and controls
45 lines (42 loc) · 1.23 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
package control;
public class Single {
/**
* This method is used to calculate the sum of the first n natural numbers.
* n exclusive
*
* @param n The number of natural numbers to sum.
* @return The sum of the first n natural numbers.
*/
public static int sumRange(int n) {
// Direct calculation using the formula for the sum of the first n natural numbers
return (n * (n - 1)) / 2;
}
/**
* This method calculates the maximum value in an array of integers.
*
* @param arr The array of integers.
* @return The maximum value in the array.
*/
public static int maxArray(int[] arr) {
if (arr == null || arr.length == 0) {
return 0; // Handle empty or null array
}
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
/**
* This method calculates the sum of the first n natural numbers, modulo m.
*
* @param n The number of natural numbers to sum.
* @param m The modulus.
*/
public static int sumModulus(int n, int m) {
int k = (n - 1) / m; // Calculate the number of multiples of m
return m * (k * (k + 1)) / 2; // Sum of multiples of m using the formula, more efficient
}
}