Skip to content
Closed
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
43 changes: 31 additions & 12 deletions code_to_optimize/java/src/main/java/com/example/Algorithms.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,41 @@
import java.util.List;

/**
* Collection of algorithms.
* Collection of algorithms that can be optimized by Codeflash.
*/
public class Algorithms {

/**
* Calculate Fibonacci number using recursive approach.
*
* @param n The position in Fibonacci sequence (0-indexed)
* @return The nth Fibonacci number
*/
public long fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
// Fast doubling iterative method (O(log n) time, O(1) space)
long a = 0; // F(0)
long b = 1; // F(1)

int highestBit = 31 - Integer.numberOfLeadingZeros(n);
for (int i = highestBit; i >= 0; i--) {
// Compute:
// c = F(2k) = F(k) * (2*F(k+1) - F(k))
// d = F(2k+1) = F(k)^2 + F(k+1)^2
long twoBminusA = (b << 1) - a;
long c = a * twoBminusA;
long d = a * a + b * b;

if (((n >> i) & 1) == 0) {
a = c;
b = d;
} else {
a = d;
b = c + d;
}
}
return a;
}

/**
* Find all prime numbers up to n.
* Find all prime numbers up to n using naive approach.
* This can be optimized with Sieve of Eratosthenes.
*
* @param n Upper bound for finding primes
* @return List of all prime numbers <= n
Expand All @@ -38,7 +54,7 @@ public List<Integer> findPrimes(int n) {
}

/**
* Check if a number is prime using trial division.
* Check if a number is prime using naive trial division.
*
* @param num Number to check
* @return true if num is prime
Expand All @@ -54,7 +70,8 @@ private boolean isPrime(int num) {
}

/**
* Find duplicates in an array using nested loops.
* Find duplicates in an array using O(n^2) nested loops.
* This can be optimized with HashSet to O(n).
*
* @param arr Input array
* @return List of duplicate elements
Expand All @@ -72,7 +89,7 @@ public List<Integer> findDuplicates(int[] arr) {
}

/**
* Calculate factorial recursively.
* Calculate factorial recursively without tail optimization.
*
* @param n Number to calculate factorial for
* @return n!
Expand All @@ -86,6 +103,7 @@ public long factorial(int n) {

/**
* Concatenate strings in a loop using String concatenation.
* Should be optimized to use StringBuilder.
*
* @param items List of strings to concatenate
* @return Concatenated result
Expand All @@ -103,6 +121,7 @@ public String concatenateStrings(List<String> items) {

/**
* Calculate sum of squares using a loop.
* This is already efficient but shows a simple example.
*
* @param n Upper bound
* @return Sum of squares from 1 to n
Expand Down
Loading