Sus Hill
Sus Hill

Reputation: 286

how to get the output value in array for further processing the output

I am trying to get the factor of a number and find the minimum distance between the factor of that number. I was trying to accomplish this process in 2 steps first finding the factors and then taking those numbers to find the minimum distance between them. I used this to find the factorial of a number

 Scanner input = new Scanner(System.in);
    int n;
    System.out.println("Enter a number");
    n = input.nextInt();
    if(n <= 0){
        System.out.println("cant input a number less than or equal to zero");
        input.close();
        return;
    }
    System.out.println("factors of " + "" + n+ "" + " are" );
    for(int i = 1; i <= n; i++){
        if(n % i == 0){
            System.out.println(i);

        }
    }

How could I get those output again for finding minimum distance between them I tried this logic

 int[] a = new int[] {i};
    Arrays.sort(a);
    int minDiff = a[1]-a[0];
    for (int i = 2 ; i != a.length ; i++) {
        minDiff = Math.min(minDiff, a[i]-a[i-1]);
    }
    System.out.println(minDiff);

My problem is, I don't know how to store those output in an array for further calculation.

Upvotes: 0

Views: 48

Answers (2)

dumbPotato21
dumbPotato21

Reputation: 5695

First, you need an ArrayList to store the factors of n. You could do something on the lines of

List<Integer> factors = new ArrayList<>();
for(int i = 1; i <= n; i++){
    if(n % i == 0){
        factors.add(i);
    }
}

Now, for finding the minimum difference, you can loop over the ArrayList, like

int minDiff = factors.get(1)-factors.get(0);
for (int i = 2 ; i < factors.size(); i++) {
    minDiff = Math.min(minDiff,factors.get(i)-factors.get(i-1));
}

Also, there is no need to sort the Array, since the factors would already be sorted.

Upvotes: 1

Jeremy Grand
Jeremy Grand

Reputation: 2370

You should create a List (A resizable array) and add the factors to it. You can then apply your logic on the list.

Get a look at :

List<Integer> factors = new ArrayList<>();  // create an empty ArrayList
    for(int i = 1; i <= n; i++){
        if(n % i == 0){
            System.out.println(i);
            factors.add(i);                 // add i to it.
        }
    }
    // we can hopefully assume that n have at least two factors (if n > 1, that is)
    // no need to sort, insertion order is kept
    int minDiff = factors.get(1) - factors.get(0);
    for (int i = 2 ; i < factors.size() ; i++) {     
        minDiff = Math.min(minDiff, factors.get(i)-factors.get(i-1));
    }
    System.out.println(minDiff);

Upvotes: 1

Related Questions