Search code examples
csortingintegerprimesfactors

Sorting integers based on their prime factors


I am kind of stuck how to sort integers based on their greatest prime factor in ascending order. For example, we have 3 and 8. The order should be: 8, 3 because 8's prime factor (2) is less than 3's prime factor (3). If we have the same greatest prime factor for 2 numbers like 9 and 27, then the smaller number should be first. In this order: 9, 27

Okay, here's my code, but it needs some modification.

long long sort(long long integers[], long long primes[]) {
    /* loop variables */
    int i, j;
    /* temporary variable */
    long long tmp;

    for (i = (SIZE - 1); i > 0; i--) {
        for (j = 1; j <= i; j++) {
            if (integers[j-1] > integers[j]) {
                tmp = integers[j-1];
                integers[j-1] = integers[j];
                integers[j] = tmp;
            }
        }
    }
}

It is also important to mention that integers[i]'s greatest prime factor is stored as primes[i]. Primes are already all set up and good, this thing only needs correct sorting.

I hope you can help me.

Thanks. :)


Solution

  • Surely you just need to use primes somewhere. In your current code you aren't using that variable at all, and it seems rather clear where it should go.

    Bonus tip: look up the standard C library function qsort.