Last active
February 6, 2025 18:20
-
-
Save MobSlicer152/5b4de0438f3754e113d9a82cdf9ecbef to your computer and use it in GitHub Desktop.
Pascal's triangle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <inttypes.h> | |
#include <math.h> | |
#include <stdbool.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <time.h> | |
#ifdef _WIN32 | |
#define WIN32_LEAN_AND_MEAN | |
#include <windows.h> | |
#endif | |
#define SEPARATOR_SIZE 2 | |
uint64_t GetMillis() | |
{ | |
#ifdef _WIN32 | |
SYSTEMTIME sysTime = { 0 }; | |
FILETIME realTime = { 0 }; | |
GetSystemTime(&sysTime); | |
SystemTimeToFileTime(&sysTime, &realTime); | |
return *(uint64_t*)&realTime / 10000; // 100-nanosecond intervals to milliseconds | |
#else | |
struct timespec now = { 0 }; | |
clock_gettime(CLOCK_MONOTONIC, &now); | |
return now.tv_sec * 1000 + now.tv_nsec / 1000000; | |
#endif | |
} | |
__forceinline long double Term(long double n, long double k, long double last) | |
{ | |
return last * (n + 1 - k) / k; | |
} | |
__forceinline uint32_t RowLength(uint32_t n) | |
{ | |
uint32_t length = 0; | |
long double last = 1; | |
for (uint32_t k = 1; k <= n; k++) | |
{ | |
last = Term(n, k, last); | |
length += floorl(log10l(last)) + SEPARATOR_SIZE; | |
} | |
return length; | |
} | |
int main(int argc, char* argv[]) | |
{ | |
uint32_t rows = 10; | |
if (argc > 1) | |
{ | |
rows = (uint32_t)strtoul(argv[1], NULL, 10); | |
} | |
uint32_t first = 0; | |
if (argc > 2) | |
{ | |
if (strcmp(argv[2], "last") == 0) | |
{ | |
first = rows; | |
} | |
first = (uint32_t)strtoul(argv[2], NULL, 10); | |
} | |
uint32_t columnLimit = 80; | |
if (argc > 3) | |
{ | |
columnLimit = (uint32_t)strtoul(argv[3], NULL, 10); | |
} | |
printf("Computing rows %d-%d (%d total)\n", first, rows, (rows - first)); | |
uint64_t start = rows > 1000 ? time(NULL) : GetMillis(); | |
uint32_t maxLength = RowLength(rows); | |
bool center = maxLength <= columnLimit; // reasonable terminal size | |
if (center) | |
{ | |
printf("Centering because last row is within column limit (%u < %u)\n", maxLength, columnLimit); | |
} | |
for (uint32_t n = first; n < rows + 1; n++) | |
{ | |
printf("row %4d: %*s", n, center ? (uint32_t)((maxLength - RowLength(n)) * 0.5) : 0, ""); | |
long double last = 1; | |
for (long double k = 1; k <= n; k++) | |
{ | |
printf("%.00Lf%*s", last, center ? SEPARATOR_SIZE : 1, ""); | |
last = Term(n, k, last); | |
} | |
printf("%.00Lf\n", last); | |
} | |
uint64_t end = rows > 1000 ? time(NULL) : GetMillis(); | |
printf("Computed %d rows in %.03fs\n", rows - first, (end - start) / (rows > 1000 ? 1.0f : 1000.0f)); | |
return rows; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment