Skip to content

Commit 46aaf4e

Browse files
committed
Add solution to Recursion problems
1 parent 6b7ede9 commit 46aaf4e

2 files changed

Lines changed: 29 additions & 19 deletions

File tree

Algorithms/Recursion/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
## [Recursion](https://www.hackerrank.com/domains/algorithms/recursion)
2+
3+
|Problem Name|Problem Link|Language|Solution Link|
4+
---|---|---|---
5+
|The Power Sum|[Problem](https://www.hackerrank.com/challenges/the-power-sum/problem)|java|[Solution](./ThePowerSum.java)|
Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,33 @@
1+
import java.io.*;
12
import java.util.*;
3+
import java.text.*;
4+
import java.math.*;
5+
import java.util.regex.*;
26

3-
/**
4-
* Created by rajat goyal on 3/19/2017.
5-
*/
7+
public class Solution {
68

7-
public class ThePowerSum {
8-
public static void main(String[] args) {
9+
static int count;
10+
public static void main(String[] args) {
911
Scanner sc = new Scanner(System.in);
1012
int x = sc.nextInt();
1113
int n = sc.nextInt();
12-
int a = (int)Math.pow(x,(1/n));
13-
System.out.println(power(x, n, a));
14+
count = 0;
15+
power(x, n, 1);
16+
System.out.println(count);
1417
}
1518

16-
public static int power(int x, int n, int a) {
17-
if(x<0) return 0;
18-
if(x==0) return 1;
19-
if(x==1) return 1;
20-
int sum = 0;
21-
for(int i=a;i>=1;i--){
22-
int temp = x-i*i;
23-
int b = (int)Math.pow(temp, (1/n));
24-
sum += power(temp, n, b);
25-
}
26-
return sum;
19+
public static void power(int x, int n, int a){
20+
if(x<0) return;
21+
if(x==0){
22+
count++;
23+
return;
24+
}
25+
int temp = (int)Math.pow(a,n);
26+
for(int i=a;temp<=x;i++){
27+
temp = (int)Math.pow(i,n);
28+
x -= temp;
29+
power(x,n,i+1);
30+
x += temp;
31+
}
2732
}
28-
}
33+
}

0 commit comments

Comments
 (0)