Created
August 16, 2018 19:55
-
-
Save mvanorder/a76f2650e71714ea33c4caa85e7660e6 to your computer and use it in GitHub Desktop.
A small program that finds the closest square root to the provided integer.
This file contains hidden or 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 <stdio.h> | |
#include <stdlib.h> | |
void main(int argc, char **argv) { | |
unsigned long n; // Input number | |
unsigned long n2; // Duplicate of input number to be worked with | |
short s = 0; // Shift counter | |
unsigned long a = 0; // Answer | |
unsigned long c = 0; // Carry number | |
n = atoi(argv[1]); // Read the first parameter provided and convert it to int | |
n = n << 8; // multiply by 10b ^ 8 to allow for rounding up | |
n2 = n; | |
/* Get the far left pair of bits and identify the index of that pair from the right */ | |
while ( n2 & ~3 ) { | |
s += 2; | |
n2 = n >> s; | |
} | |
do { | |
c = a << 2; // Carry becomes answer * 2 plus an extra digit | |
a = a << 1; // New answer is old answer with an extra digit | |
if ((c | 1u) <= n2) { // If Carry + 1 isn't greater than the remainder: | |
a = a | 1u; // Add 1 to answer | |
n2 -= c | 1u; // Subtract carry + 1 from remainder | |
} | |
n2 = n2 << 2; // Shift remainder 2 digits | |
s -= 2; // Deincriment shift counter | |
n2 += (n >> s) & 3; // Add the next pair of digits to remainder for next round | |
} while (~s & -2); // Repeat until shift counter reaches 0, then one more time | |
if ((a & 15) >= 8) { // Round to the next whole number | |
a += 8; | |
} | |
a = a >> 4; // Divide by 10b ^ 4 after rounding | |
printf("%u\n", a); // Print the result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment