I tried HackerRank’s Project Euler Problem #1: Multiples of 3 and 5:
Project Euler #1
My code is in Java. I tried to solve this using recursion:
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
for (int i = 0; i < cases; i++) {
int n = scanner.nextInt();
int sum = calculateSum((n % 3 == 0) ? n - 3 : n - (n % 3), 3) +
calculateSum((n % 5 == 0) ? n - 5 : n - (n % 5), 5) -
calculateSum((n % 15 == 0) ? n - 15 : n - (n % 15), 15);
System.out.println(sum);
}
}
private static int calculateSum(int n, int f) {
if (n <= 0) {
return 0;
}
return n + calculateSum(n - f, f);
}
}
It shows runtime error for hidden cases 2 and 3:
Test Cases Result
New contributor
Parth Shrivastava is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.