Skip to content

Instantly share code, notes, and snippets.

@korotkevics
Created November 27, 2016 18:07
Show Gist options
  • Save korotkevics/92265b83c1cabe79826b3ffb86df7523 to your computer and use it in GitHub Desktop.
Save korotkevics/92265b83c1cabe79826b3ffb86df7523 to your computer and use it in GitHub Desktop.
Uni samples.
//
// Created by Sandor Korotkevics on 27.11.16.
//
#include <stdio.h>
int greatestCommonDivisor(int first, int second);
int fibonacci(int limit);
typedef struct { //Experiments with typedef struct.
int actual;
int first;
int second;
int limit;
} resultFibonacci;
int main(void)
{
//Greatest Common Divisor - no remainder.
greatestCommonDivisor(6,9);
//Greatest Common Divisor - with a remainder.
greatestCommonDivisor(3,5);
//Fibonacci
fibonacci(10);
}
int greatestCommonDivisor(int first, int second) {
int theLargest;
int theSmallest;
int commonDivisor;
int isFound = 0;
if (first>second) {
theLargest = first;
theSmallest = second;
} else {
theLargest = second;
theSmallest = first;
}
while (isFound!=1) {
printf("The largest.. %d\n", theLargest);
printf("The smallest.. %d\n", theSmallest);
if (theLargest>theSmallest) {
theLargest = theLargest - theSmallest;
} else {
isFound = 1;
commonDivisor = theLargest;
}
}
printf("The greatest common divisor .. %d\n", commonDivisor);
if (theSmallest%commonDivisor != 0) {
printf("NOTE! It is an approximate match.\n"); //E.g. first=5, second=3.
} else {
printf("You are lucky!"); //E.g. first = 6, second = 9.
}
return commonDivisor;
}
int fibonacci(int limit) {
if (limit<0) {
printf("The limit has to be a positive number.\n");
return 0;
}
if (limit==0) {
return 0;
}
if (limit==1) {
return 1;
}
resultFibonacci result;
result.first = 0;
result.second = 1;
result.limit = limit;
for (int counter = 2; counter <= result.limit; counter++) {
result.actual = result.first + result.second;
if (counter!=result.limit) { //Keep two previous nrs in the last loop.
result.first = result.second;
result.second = result.actual;
printf("Current nr..%d\n", result.actual);
}
}
printf("Success!\n");
printf("Fibonacci %d\n",result.actual);
printf("Previous nr.. %d\n", result.second);
printf("Previous nr.. %d\n", result.first);
return result.actual;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment