Skip to content

01: Introduction to C

Hello World

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
}

Count Primes

#include <stdio.h>

/* Subtask: is a particular integer a prime number
 * Input: an integer n
 * Output: Yes (1) or No (0) */
// Repeat for j from 2 to floor(n/2):
//   if n is divisible by j:
//      subtask returns false, and quit
// subtask returns true, and quit
int IsPrime(int n) {
    for (int j = 2; j <= (n/2); j++) {
    if (n % j == 0)
        return 0;
    }
    return 1;
}


/* Main task: count the number of prime numbers up to 200000 */
// counter <-- 0
// Repeat for i from 2 to 200000
//   is i a prime number?
//   if yes, increment counter by 1
// Printout result
int main() {
    int num_primes = 0;
    for (int i = 2; i <= 200000; i++) {
    num_primes += IsPrime(i);
    }
    printf("%d\n", num_primes);
}

Python version:

def isPrime(n):
    for j in range(2, n//2 + 1):
        if not(n % j):
            return 0
    return 1

num_primes = 0
for i in range (2, 200001):
    num_primes += isPrime(i)

print(str(num_primes))

Sumup

This example shows the exact instructions run by Python.

def sumup(n):
    s = 0
    for i in range(1, n):
        s += i
    return s

import dis
dis.dis(sumup)