Week1 - Data Structures and Algorithms - Financial Forecasting
Week1 - Data Structures and Algorithms - Financial Forecasting
CODE:
FinancialForecast.java:
public class FinancialForecast {
// Recursive method to calculate future value
public static double forecast(double currentValue, double growthRate, int years) {
if (years == 0) {
return currentValue;
}
return forecast(currentValue * (1 + growthRate), growthRate, years - 1);
}
// Optimized version with memoization (optional)
public static double forecastOptimized(double currentValue, double growthRate, int years)
{
return currentValue * power(1 + growthRate, years);
}
// Helper function to calculate power recursively
private static double power(double base, int exponent) {
if (exponent == 0) return 1;
double half = power(base, exponent / 2);
if (exponent % 2 == 0) return half * half;
return base * half * half;
}
}
ForecastTest.java:
public class ForecastTest {
public static void main(String[] args) {
double currentValue = 10000;
double growthRate = 0.08;
int years = 5;
double futureValue = FinancialForecast.forecast(currentValue, growthRate, years);
System.out.printf("Recursive Forecast (%.0f at %.2f%% for %d years): %.2f%n",
currentValue, growthRate * 100, years, futureValue);
double optimizedValue = FinancialForecast.forecastOptimized(currentValue,
growthRate, years);
System.out.printf("Optimized Forecast: %.2f%n", optimizedValue);
}
}
OUTPUT: