Problem:
Given an int N, calculate the sum of series 13+23+33+43…… till the nth term using recursion (Link to problem)
Implemented Solution in Python:
<code>#User function Template for python3
class Solution:
def sumOfSeries(self,n):
#code here
if n>0:
return (n*n*n) + self.sumOfSeries(n-1)
else:
return 0
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__=='__main__':
t=int(input())
for _ in range(t):
N=int(input())
ob=Solution()
print(ob.sumOfSeries(N))
# } Driver Code Ends
</code>
<code>#User function Template for python3
class Solution:
def sumOfSeries(self,n):
#code here
if n>0:
return (n*n*n) + self.sumOfSeries(n-1)
else:
return 0
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__=='__main__':
t=int(input())
for _ in range(t):
N=int(input())
ob=Solution()
print(ob.sumOfSeries(N))
# } Driver Code Ends
</code>
#User function Template for python3
class Solution:
def sumOfSeries(self,n):
#code here
if n>0:
return (n*n*n) + self.sumOfSeries(n-1)
else:
return 0
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__=='__main__':
t=int(input())
for _ in range(t):
N=int(input())
ob=Solution()
print(ob.sumOfSeries(N))
# } Driver Code Ends
The solution works for small inputs but is giving the above error of large values like 18468
I am unable understand the meaning of the error and what is causing it
I attempted to solve the same problem using recursion in C++ and it is not presenting any error
C++ Solution:
<code>//{ Driver Code Starts
// Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template for C++
class Solution {
public:
long long sumOfSeries(long long n) {
// code here
if (n==1)
return 1;
else
return (n*n*n)+sumOfSeries(n-1);
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
long long N;
cin >> N;
Solution ob;
cout << ob.sumOfSeries(N) << "n";
}
}
// } Driver Code Ends
</code>
<code>//{ Driver Code Starts
// Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template for C++
class Solution {
public:
long long sumOfSeries(long long n) {
// code here
if (n==1)
return 1;
else
return (n*n*n)+sumOfSeries(n-1);
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
long long N;
cin >> N;
Solution ob;
cout << ob.sumOfSeries(N) << "n";
}
}
// } Driver Code Ends
</code>
//{ Driver Code Starts
// Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template for C++
class Solution {
public:
long long sumOfSeries(long long n) {
// code here
if (n==1)
return 1;
else
return (n*n*n)+sumOfSeries(n-1);
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
long long N;
cin >> N;
Solution ob;
cout << ob.sumOfSeries(N) << "n";
}
}
// } Driver Code Ends