java - How can I get largest prime factors between two numbers and store them in an array? -
i've been asked solve question:
write function takes 2 numbers
n1
,n2
input (withn2>n1
) , returns array of largest prime factors corresponding each number betweenn1
,n2
.
my attempt shown below, code not working properly. not iterating n1
n2
. how can right?
public static class a{ static int testcase1=5; static int testcase2=10; public static void main(string args[]){ testinstance = new a(); int[] result = testinstance.getlpfd(testcase1,testcase2); system.out.print("{"); (int i=0;i<result.length;i++){ if (i>0) system.out.print(","); system.out.print(result[i]); } system.out.println("}"); } public int[] getlpfd(int n1,int n2){ int current=0; int[] factors = new int[20]; for(int j=n1;j<=n2;j++){ (int = 2; <= j; i++){ while(j % == 0){ factors[current]=i; j /= i; current++; } } } return factors; } } }
it's easiest separate task of finding factors task of writing largest factor. here function find factors:
function factors(n) f, fs := 2, [] while f * f <= n while n % f == 0 insert f @ head of fs n := n / f f := f + 1 if n > 1 insert n @ head of fs return fs
that returns factors of n in descending order, largest factor @ head of list. easy accumulate list of largest prime factors of range:
function lpf(lo, hi) result := makearray(0 .. hi-lo) n lo hi result[n-lo] := head(factors(n)) return result
i'll leave translate java.
if range large, variant of sieve of eratosthenes faster computing factors.
Comments
Post a Comment