Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 7 additions & 19 deletions app/src/main/java/control/Single.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,8 @@ public class Single {
* @return The sum of the first n natural numbers.
*/
public static int sumRange(int n) {
int[] arr = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
arr[i] = i;
}
for (int i : arr) {
sum += i;
}
return sum;
// Direct calculation using the formula for the sum of the first n natural numbers
return (n * (n - 1)) / 2;
}

/**
Expand All @@ -29,7 +22,8 @@ public static int sumRange(int n) {
* @return The maximum value in the array.
*/
public static int maxArray(int[] arr) {
int max = 0;
// Initialize max to the smallest possible integer value
int max = Integer.MIN_VALUE;
for (int i : arr) {
if (i > max) {
max = i;
Expand All @@ -45,13 +39,7 @@ public static int maxArray(int[] arr) {
* @param m The modulus.
*/
public static int sumModulus(int n, int m) {
Vector<Integer> multiples = new Vector<Integer>();
for (int i = 0; i < n; i++) {
if (i % m == 0) {
multiples.add(i);
}
}

return multiples.stream().mapToInt(Integer::valueOf).sum();
int k = (n - 1) / m; // Calculate the number of multiples of m
return m * (k * (k + 1)) / 2; // Sum of multiples of m
}
}
}