algorithm - Prime factors using recursion in Java -
i'm having trouble recursion in java. have following method , should transform recursion without loop.
public static list<integer> primesloop(int n) { list<integer> factors = new arraylist<integer>(); int f = 2; while (f <= n) if (n % f == 0) { factors.add(f); n /= f; } else f++; return factors; }
the recursive method should start same form:
public static list<integer> primesrec(int n);
and should define methods transformation result example:
primesrec(900) -> prime factors of 900 : [2, 2, 3, 3, 5, 5]
you can add f
argument overloading, , adding private method take it, , invoked "main" public method.
in private method, have 3 cases:
- stop clause: n==1: create new empty list
- n%f == 0: recurse n'=n/f, f'=f, , add
f
list. - n%f != 0: recurse n'=n, f'=f+1, don't add list.
code:
public static list<integer> primesrecursive(int n) { return primesrecursive(n,2); } //overlaod private method takes f argument: private static list<integer> primesrecursive(int n, int f) { if (n == 1) return new arraylist<integer>(); if (n % f == 0) { list<integer> factors = primesrecursive(n/f, f); factors.add(f); return factors; } else return primesrecursive(n,f+1); }
as expected, invoking:
public static void main(string args[]) { system.out.println(primesrecursive(900)); }
will yield:
[5, 5, 3, 3, 2, 2]
note: if want factors in ascending order:
- switch
arraylist
implementationlinkedlist
in stop clause (for performance issues) - add items
factors.add(0,f);
insteadfactors.add(f)
Comments
Post a Comment