Basics of Programming 1 solutions

Week 2 correction

My solution to last week's fourth task was unnecessarily complicated. We can take note of two useful properties of prime factorisation.

  1. If we're iterating starting from 2, every divisor we find will always be prime, since we would've found an integer disproving its prime status earlier.
  2. We do not need to restart from 2 once we found a prime divisor of the original number, since the next factor can only be equal to or larger than the previous one.

I'm taking this opportunity to publish a corrected version of my original code.

#include <stdio.h>
#include <stdbool.h>

//no prime check needed

int main() {
    int x = 42;
    int i = 2;
    printf("%d|", x);
    while(x > 1) {
        if (x % i == 0) {
            printf("%d\n", i);
            x /= i;
            printf("%d|", x);
        } else i += 1;
    }
    return 0;
}