0% found this document useful (0 votes)
2 views2 pages

Week1 - Data Structures and Algorithms - Financial Forecasting

The document contains Java code for a financial forecasting application that calculates future values based on a given current value, growth rate, and number of years. It includes a recursive method for forecasting and an optimized version using memoization with a helper function for calculating powers. The main class demonstrates the usage of both forecasting methods with sample data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Week1 - Data Structures and Algorithms - Financial Forecasting

The document contains Java code for a financial forecasting application that calculates future values based on a given current value, growth rate, and number of years. It includes a recursive method for forecasting and an optimized version using memoization with a helper function for calculating powers. The main class demonstrates the usage of both forecasting methods with sample data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Exercise 7: 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:

You might also like