Fibonacci Numbers in c - c

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
/* number of max three digits (max digits = MAX3DIGITS*3) */
#define MAX3DIGITS 100000
/* struct that holds three digits (like 503) */
struct three {
unsigned n : 10;
};
/* a whole number made up of struct threes */
struct num {
struct three n[MAX3DIGITS];
} number[2];
FILE *dg;
int main() {
int naim;
dg=fopen("deneme.txt","w");
for(naim=1;naim<1001;naim++){
int prev = 0;
int x, y, n = 0;
int digits = 2;
number[0].n[0].n = 0;
number[1].n[0].n = 1;
while(!kbhit() && ++n < naim && digits <= MAX3DIGITS) {
//fprintf(stderr, "\r%i", n);
prev = !prev;
for(x = 0; x < digits; x ++) {
y = number[!prev].n[x].n + number[prev].n[x].n;
number[!prev].n[x].n = (y%1000);
number[!prev].n[x+1].n += (y/1000);
}
if(number[!prev].n[digits-1].n) digits ++;
}
fprintf(dg,"\nfib(%i) = %i", n, number[!prev].n[digits-2].n);
for(x = digits-3; x >= 0; x --) {
fprintf(dg,"%03i", number[!prev].n[x].n);
}
fprintf(dg,"\n");
}
printf("sad");
if(kbhit()) getche();
getchar();
getchar();
return 0;
}
This code is writing first 1000 Fibonacci numbers. But my problem is starting 18th number. Until seventeenth number , this code is working. But 18th number is wrong so remaining is wrong. How can I fix it ?
Thank You.

Instead of issuing considerations on the code, I'll just answer the question.
The problem is that you have to initialize (to zero) the memory you're using to store the two numbers. Following a working version of your code, my two small modifications sandwiched between // * comments.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
// *****
#include <mem.h>
// *****
/* number of max three digits (max digits = MAX3DIGITS*3) */
#define MAX3DIGITS 100000
/* struct that holds three digits (like 503) */
struct three {
unsigned n : 10;
};
/* a whole number made up of struct threes */
struct num {
struct three n[MAX3DIGITS];
} number[2];
FILE *dg;
int main() {
int naim;
dg=fopen("deneme.txt","w");
for(naim=1;naim<1001;naim++){
int prev = 0;
int x, y, n = 0;
int digits = 2;
// *****
memset(number, 0, sizeof(number));
// *****
number[0].n[0].n = 0;
number[1].n[0].n = 1;
while(!kbhit() && ++n < naim && digits <= MAX3DIGITS) {
//fprintf(stderr, "\r%i", n);
prev = !prev;
for(x = 0; x < digits; x ++) {
y = number[!prev].n[x].n + number[prev].n[x].n;
number[!prev].n[x].n = (y%1000);
number[!prev].n[x+1].n += (y/1000);
}
if(number[!prev].n[digits-1].n) digits ++;
}
fprintf(dg,"\nfib(%i) = %i", n, number[!prev].n[digits-2].n);
for(x = digits-3; x >= 0; x --) {
fprintf(dg,"%03i", number[!prev].n[x].n);
}
fprintf(dg,"\n");
}
printf("sad");
if(kbhit()) getche();
getchar();
getchar();
return 0;
}

Related

How to check to make sure there are no repeats when generating 6 random numbers?

I can get the random numbers into an array but I can't figure out how to check to make sure that they aren't repeating. I print out the code but there are no numbers in the array (prints out nothing).
//puts random numbers into an array
i = 0, j = 0;
srand(time(NULL));
for (i = 0; i < arrSize; i++)
{
randArr[i] = randNums(1,50);
}
i = 0;
for(i = 0; i < arrSize; i++)
{
printf("%d ", randArr[i]);
}
printf("\n\n");
//checks to make sure there are no duplicates
i = 0, j = 0, k = 0, temp = 0;
for (i = 0; i < arrSize; i++)
{
for (j = 1; j <= arrSize;)
{
if (randArr[j] == randArr[i])
{
for (k = j; k <= arrSize; k++)
{
temp = randNums(1,50);
randArr[k + 1] = temp;
}
arrSize--;
}
else
j++;
}
}
//generates random numbers between the inputed max and min
int randNums(int min, int max)
{
int result = 0, low = 0, high = 0;
if (min < max)
{
low = min;
high = max + 1;
}
else
{
low = max + 1;
high = min;
}
result = (rand() % (high - low)) + low;
return (result);
}
Beware! There are many different solutions to this problem and they all have one or another downside. If I was to quickly implement it, I would go for something like this (without too much C-magic going on):
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE (30)
#define RAND_MIN (1)
#define RAND_MAX (50)
static int randNums(int min, int max) {
// ...
}
int main(void) {
(void) srand(time(NULL));
int arr[SIZE];
int used = 0;
while (used < SIZE) {
int num = randNums(RAND_MIN, RAND_MAX);
bool exists = false;
for (int i = 0; i < used; ++i) {
if (arr[i] == num)
exists = true;
}
if (exists == false)
arr[used++] = num;
}
for (int i = 0; i < SIZE; ++i)
(void) printf("%d\n", arr[i]);
return EXIT_SUCCESS;
}
I hope it helps a bit :)
Like this answer, you can do rejection sampling, but the uniform distribution of a fixed number of samples is perfect for a very simple hash set. (Though the asymptotic runtime might be irrelevant for n=6.)
#include <stdlib.h> /* (s)rand */
#include <stdio.h> /* printf */
#include <time.h> /* clock */
#include <assert.h> /* assert */
/* Double-pointers are confusing. */
struct Reference { int *ref; };
/* Simple fixed hash set. */
static struct Reference bins[256];
static int nums[6];
static const size_t no_bins = sizeof bins / sizeof *bins,
no_nums = sizeof nums / sizeof *nums;
static size_t count_num;
/* Uniformly distributed numbers are great for hashing, but possibly clump
together under linear probing. */
static size_t hash(const int n) { return ((size_t)n * 21) % no_bins; }
/* Linear probing. */
static struct Reference *probe(const int n) {
size_t bin_index;
struct Reference *bin;
assert(sizeof bins > sizeof nums);
for(bin_index = hash(n); bin = bins + bin_index,
bin->ref && *bin->ref != n; bin_index = (bin_index + 1) % no_bins);
return bin;
}
/* Return whether it's a new value. */
static int put_in_set(const int n) {
struct Reference *bin = probe(n);
int *num;
assert(count_num < no_nums);
if(bin->ref) return 0; /* Already in hash. */
num = nums + count_num++;
*num = n;
bin->ref = num;
return 1;
}
/* http://c-faq.com/lib/randrange.html */
static int rand_range(const unsigned n) {
unsigned int x = (RAND_MAX + 1u) / n;
unsigned int y = x * n;
unsigned int r;
assert(n > 0);
do {
r = rand();
} while(r >= y);
return r / x;
}
/* Generates random numbers between the inputed max and min without
repetition; [min, max] inclusive. */
static int unique_uniform(const int min, const int max) {
int n;
assert(min <= max && (size_t)(max - min) >= count_num);
do { n = rand_range(max - min + 1) + min; } while(!put_in_set(n));
return n;
}
int main(void) {
int n = 6;
srand((int)clock()), rand(); /* My computer always picks the same first? */
while(n--) { printf("%d\n", unique_uniform(1, 50)); }
return EXIT_SUCCESS;
}
However, if the numbers are densely packed, (eg, unique_uniform(1, 6),) it's going to reject a lot of numbers. Another solution is to take a Poisson distributed numbers as a running sum, (recurrence T(n+1)=T(n)+\mu_{n+1},) where the expected value is the range of numbers divided by the total samples, then take a random permutation.

C program to print numbers between 100 and 1000 which sum of digit is 20

I am writing a C program which should display me all numbers between 100 and 1000 which sum of digit is 20. I tried this code down here, but it just displays 0 as an ouput when I compile it, can you help me? I also tried moving if(iVsota==20) outside of the while loop. I am using Orwell Dev C++ IDE.
#include <stdio.h>
int main (void)
{
int iVnos=0;
int iOstanek=0;
int iVsota=1;
int iStevec1=100;
for(iStevec1=100; iStevec1<1000; iStevec1++)
{
while(iStevec1>0)
{
iOstanek=iStevec1%100;
iStevec1=iStevec1/10;
iVsota=iOstanek+iVsota;
if(iVsota==20)
{
printf("%i\n", iStevec1);
}
}
}
return(0);
I hope this is better.
Your loop should look like :
for(iStevec1=100; iStevec1<1000; iStevec1++)
{
int c2 = iStevec1/100; // extract third digit
int c1 = (iStevec1%100)/10; // extract second digit
int c0 = (iStevec1%10); // extract first digit
if((c0+c1+c2)==20) // sum and verify
{
printf("%i\n", iStevec1);
}
}
This should work for you:
(Changed the variable names so it's more readable)
#include <stdio.h>
int add_digits(int n) {
static int sum = 0;
if (n == 0)
return 0;
sum = n%10 + add_digits(n/10);
return sum;
}
int main() {
int start, end;
start = 100, end = 1000;
for(start = 100; start <= end; start++) {
if(add_digits(start) == 20)
printf("Number: %d\n", start);
}
return 0;
}
EDIT:
(Your code fixed with comments as explanation)
#include <stdio.h>
int main() {
int iVnos=0;
int iOstanek=0;
int iVsota=0;
int iStevec1=100;
int temp; //temp needed
for(iStevec1=100; iStevec1<=1000; iStevec1++)
{
temp =iStevec1; //assign number to temp
iVsota=0; //set sum every iteration to 0
while(temp>0)
{
iOstanek=temp%10; //You need only % 10 to get the last digit of a number
temp = temp / 10; //'delete' last digit of the number
iVsota+=iOstanek; //add digit to sum
}
if(iVsota==20) //You only need to check the digits after sum is calculated
printf("Number %d\n", iStevec1);
}
return 0;
}
Here's a more generalised method to get the sum of all individual numbers in an integer (assumes positive integers):
int getSumOfDigits(int x)
{
int sum = 0;
while (x > 0)
{
sum += x % 10;
x = x / 10;
}
return sum;
}
int main()
{
for (int i = 100; i <= 1000; i++)
{
if (getSumOfDigits(i) == 20)
{
printf("%d\n", x);
}
}
}
The expression x % 10 is the last digit in the integer. Hence, that's what we add. Then we chop off the last digit in the integer by dividing it by 10. Repeat until we hit zero.
Alternative method, taking advantage of the specifics.
#include <stdio.h>
int main()
{
int c0, c1, c2; /* 3 digits sum to 20 */
for(c0 = 2; c0 < 10; c0++){
c1 = 11 - c0;
c2 = 9;
while(c1 < 10){
printf("%d%d%d\n", c0, c1, c2);
/* or printf("%3d\n", (c0*10+c1)*10+c2); */
c1++;
c2--;
}
}
return(0);
}
Just change 1 thing and you will get what you want
int main (void)
{
int iVnos=0;
int iOstanek=0;
int iVsota=1;
int iStevec1=100;
int temp;
for(iStevec1=100; iStevec1<1000; iStevec1++)
{
temp = iStevec1;
while(temp>0)
{
iOstanek=temp%100;
temp=temp/10;
iVsota=iOstanek+iVsota;
if(iVsota==20)
{
printf("%i\n", iStevec1);
}
}
}
return(0);
}
Enjoy Coding Enjoy Life...

rand() doesn't follow Gaussian Distribution & Central Limit Theorem

I've created a program that use rand() to generate repeated number in C.
However the repeated number doesn't follow Central Limit Theorem
Can anyone solve this rand() bug problem or is there an alternative other than using rand() C library to generate better random number?
Here's the screen shot:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#define TOTAL_THROW 10000000
typedef enum _COINTOSS {
UNDEFINED = 0,
HEAD = 1,
TAIL = 2
} COINTOSS;
COINTOSS toss_coin () {
int x = rand() % 2;
if (x == 0) return HEAD;
else if (x == 1) return TAIL;
}
void main () {
int x, i, j, v1 = 0, v2 = 200, total = 0;
int head_range[25] = {0};
int tail_range[25] = {0};
int no_range = 0;
int count = 0;
int repeated = 0;
COINTOSS previos_toss = UNDEFINED;
COINTOSS current_toss;
srand(time(NULL));
for (i=0; i<TOTAL_THROW; i++) {
current_toss = toss_coin(); // current toss
if (previos_toss == current_toss) {
count++;
} else {
if (current_toss == HEAD) head_range[count] += 1;
else if (current_toss == TAIL) tail_range[count] += 1;
previos_toss = current_toss;
count = 0;
}
}
for (i=24; i>=0; i--) {
printf("+%d = %d\n", i+1, head_range[i]);
}
puts("________________\n");
for (i=0; i<25; i++) {
printf("-%d = %d\n", i+1, tail_range[i]);
}
printf("\nTOTAL_THROW: %d\n", TOTAL_THROW);
printf("\nPress [ENTER] to exit. . .");
getchar();
}
Your problem is using modulus to get your random number into the required range, which uses the lower bits (it's a classic gotcha):
int x = rand() % 2;
The lower bits of rand() (a linear congruential generator (LCG)) are not as random as the high bits. This applies to all LCG's regardless of library or language.
For a range of [0..N), you should do something like this (which uses the high bits):
int r = rand() / ( RAND_MAX / N + 1 );

Shorter way to get 5 highest and 5 lowest values without changing the stack

So here is my code . I am trying to find a short way to make this programme work withouth changing any of the arregment.I have been tought the buble way i think its called to arrange a group from highest to lowest but it clearly say in my given orders not to change the entire group.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int randomInRange (unsigned int min, unsigned int max)
{
//srand(time(NULL));
int base_random = rand();
if (RAND_MAX == base_random) return randomInRange(min, max);
int range = max + 1 - min,
remainder = RAND_MAX % range,
bucket = RAND_MAX / range;
if (base_random < RAND_MAX - remainder) {
return min + base_random/bucket;
} else {
return randomInRange (min, max);
}
}
int main()
{
int ari,i,min,max;
printf("Gi'me length of the group")
scanf("%d",&ari);
int pinakas[ari];
printf("Gi'me lowest and highest values");
scanf("%d",&min);
scanf("%d",&max);
for(i = 0; i < ari; i++)
{
pinakas[ari] = randomInRange(min,max);
}
int el,meg,c;
el = max+1;
meg = min-1;
c = 0;
printf("Highest Lowest");
while( c != 4;)
{
for(i = 0; i < ari; i++)
{
if(el > pinakas[ari])
{
el = pinakas[ari];
}
if( meg < pinakas[ari])
{
meg = pinakas[ari];
}
if(i == 4)
{
printf("%d %d",el,meg);
( is there something that i can put here is order to make el,meg to go for the second lowest ,second highest? and so on till i get the 5 highest and 5 lowests.Keep in mind the the lowest length of my group will be pinakas[5].)
}
}
c++;
}
For each item in the array, up to 5 comparisons are done for the min list and 5 for the max list.
Suggest calling a function to do this in a tidy fashion.
#include<assert.h>
// `list` is `const` as OP says "withouth changing any of the arregment".
void sort_ends(const int *list, size_t listlen, int *minlist, int *maxlist,
size_t mlen) {
assert(list);
assert(minlist);
assert(maxlist);
assert(mlen >= 1);
assert(listlen >= mlen);
minlist[0] = list[0];
// For each element after the first ...
for (size_t i = 1; i < listlen; i++) {
int mincandidate = list[i];
size_t mini = i;
if (mini > mlen) mini = mlen;
do {
mini--;
if (mincandidate >= minlist[mini])
break;
// swap mincandidate and minlist[mini]
int t = mincandidate;
mincandidate = minlist[mini];
minlist[mini] = t;
} while (mini > 0);
}
// Do similar for maxlist, left for OP
}
int main() {
int ari;
// ...
int pinakas[ari];
// ...
int mlen = 5;
int minlist[mlen];
int maxlist[mlen];
sort_ends(pinakas, ari, minlist, maxlist, mlen);
return 0;
}
Alternative approach, find min index and then memove().

convert an integer number into an array

I am trying to convert an integer number in C into an array containing each of that number's digits
i.e. if I have
int number = 5400
how can I get to
int numberArray[4]
where
numberArray[0] = 0;
numberArray[1] = 0;
numberArray[2] = 4;
numberArray[3] = 5;
Any suggestions gratefully received.
This would work for numbers >= 0
#include <math.h>
char * convertNumberIntoArray(unsigned int number) {
int length = (int)floor(log10((float)number)) + 1;
char * arr = new char[length];
int i = 0;
do {
arr[i] = number % 10;
number /= 10;
i++;
} while (number != 0);
return arr;
}
EDIT: Just a little bit more C style but more cryptic.
#include <math.h>
char * convertNumberIntoArray(unsigned int number) {
unsigned int length = (int)(log10((float)number)) + 1;
char * arr = (char *) malloc(length * sizeof(char)), * curr = arr;
do {
*curr++ = number % 10;
number /= 10;
} while (number != 0);
return arr;
}
Hint: Take a look at this earlier question "Sum of digits in C#". It explains how to extract the digits in the number using several methods, some relevant in C.
From Greg Hewgill's answer:
/* count number of digits */
int c = 0; /* digit position */
int n = number;
while (n != 0)
{
n /= 10;
c++;
}
int numberArray[c];
c = 0;
n = number;
/* extract each digit */
while (n != 0)
{
numberArray[c] = n % 10;
n /= 10;
c++;
}
You could calculate the number of digits in an integer with logarithm rather than a loop. Thus,
int * toArray(int number)
{
int n = log10(number) + 1;
int i;
int *numberArray = calloc(n, sizeof(int));
for ( i = 0; i < n; ++i, number /= 10 )
{
numberArray[i] = number % 10;
}
return numberArray;
}
Try this,
void initialise_array(int *a, int size, int num) {
for (int i = 0; i < size; ++i, num /= 10)
a[(size - 1) - i] = num % 10;
}
If you need to take negative numbers into account, you might need some extra logic. In fact, when playing around with arrays you don't know the size of upfront, you may want to do some more safety checking, and adding an API for handling the structure of the data is quite handy too.
// returns the number of digits converted
// stores the digits in reverse order (smalles digit first)
// precondition: outputdigits is big enough to store all digits.
//
int convert( int number, int* outputdigits, int* signdigit ) {
int* workingdigits = outputdigits;
int sign = 1;
if( number < 0 ) { *signdigit = -1; number *= -1; }
++workingdigits;
for ( ; number > 0; ++ workingdigits ) {
*workingdigits = number % 10;
number = number / 10;
}
return workingdigits - outputdigits;
}
void printdigits( int* digits, int size, int signdigit ) {
if( signdigit < 0 ) printf( "-" );
for( int* digit = digits+size-1; digit >= digits; --digit ){
printf( "%d", *digit );
}
}
int main() {
int digits[10];
int signdigit;
printdigits( digits, convert( 10, digits, &signdigit ), signdigit );
printdigits( digits, convert( -10, digits, &signdigit ), signdigit );
printdigits( digits, convert( 1005, digits, &signdigit ), signdigit );
}
#include <stdio.h>
#include <string.h>
int main(void)
{
int i, inputNumber;
char* charArray;
printf("\nEnter number: ");
scanf("%d", &inputNumber);
/* converts int to print buffer which is char array */
sprintf(charArray, "%d", inputNumber);
int size = strlen(charArray);
int intArray[size];
for (i = 0; i < size; i++)
{
intArray[i] = charArray[i] - '0';
}
return 0;
}
C code:
/* one decimal digit takes a few more than 3 bits. (2^3=8, 2^4=16) */
int digits[(sizeof (int) * CHAR_BIT) / 3 + 1],
*digitsp = digits;
do {
*digitsp++ = number % 10;
number /= 10;
} while(number > 0);
You will see how many digits you converted by taking the difference
digitsp - digits
If you want to put it into a function:
#define MIN_DIGITS_IN_INT ((sizeof (int) * CHAR_BIT) / 3 + 1)
int to_array(int number, int *digits) {
int *digitsp = digits;
do {
*digitsp++ = number % 10;
number /= 10;
} while(number > 0);
return digitsp - digits;
}
int main() {
int number = rand();
int digits[MIN_DIGITS_IN_INT];
int n = to_array(number, digits);
/* test whether we're right */
while(n-- > 0)
printf("%d", digits[n]);
}
printf(" = %d\n", number);
}
I prefer automatic arrays to dynamic memory allocation in this case, since it's easier to do it right and not leak accidentally.
using vadim's code, I came up with this test program:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
char * convertNumberIntoArray(unsigned int number) {
unsigned int length = (int)(log10((float)number)) + 1;
char * arr = (char *) malloc(length * sizeof(char)), * curr = arr;
do {
*curr++ = number % 10;
number /= 10;
} while (number != 0);
return arr;
}
int main(void)
{
int InputNumber;
int arr[5];
printf("enter number: \n");
scanf("%d", &InputNumber);
convertNumberIntoArray(InputNumber);
printf("The number components are: %d %d %d\n", arr[0],arr[1],arr[2]);
system("PAUSE");
return 0;
}
but the output is garbage. Can anyone advise if I have done something stupid here?
/***** output *****/
enter number:
501
The number components are: 2009291924 2009145456 -1
Press any key to continue . . .
--dave

Resources