Print Factors of a Number in C – O(√n) Algorithm

A C program to print factors of a number finds all positive integers that divide the number evenly (with no remainder). These are also called divisors. For 12: the factors are 1, 2, 3, 4, 6, and 12. Every number has at least two factors: 1 and itself. A number with exactly two factors is …

Topological Sort in C — Kahn’s Algorithm with Cycle Detection

Topological sort orders the vertices of a directed acyclic graph (DAG) so that every edge points forward: if there’s an edge from u to v, then u appears before v in the ordering. It’s the algorithm behind every dependency system you’ve used — build tools compiling files in the right order, package managers resolving installs, …

K&R C Exercise 3-6: itoa with Minimum Field Width

Exercise 3-6. Write a version of itoa that accepts three arguments instead of two. The third argument is a minimum field width; the converted number must be padded with blanks on the left if necessary to make it wide enough. This is exactly what printf‘s %6d format does — the 6 is a minimum field …

K&R C Exercise 3-5: itob — Integer to Any Base String

Exercise 3-5. Write the function itob(n,s,b) that converts the integer n into a base b character representation in the string s. In particular, itob(n,s,16) should produce in s a hexadecimal string. itob generalises itoa from base 10 to any base 2–36. The only change to the digit-extraction loop is replacing n % 10 with n …

K&R C Exercise 3-4: itoa — Handle INT_MIN in Integer to String

Exercise 3-4. In a two’s complement number representation, our version of itoa does not handle the largest negative number, that is, the value of n equal to −(2wordsize−1). Explain why not. Modify it to print that value correctly, regardless of the machine on which it runs. This exercise has two parts: explain the bug, then …

System Information in C — getenv(), system(), and uname()

How do you get system information from a C program? There are three portable-ish layers, and knowing which to use is the actual lesson: getenv() reads environment variables (pure standard C), system() runs a shell command like uname (standard C, but it launches a whole shell), and POSIX uname() fills a struct with OS name, …