I am constructing a C program which prints Fibonacci numbers into a file and finds the median.
The output I am getting is a very large and incorrect number. Any insight would be great.
Median Function C
int findMedian(FILE *file, int size)
{
int medianPos, medianVal, readVal, count;
medianPos = (size / 2);
count = 0;
while(fscanf(file,"%d", &readVal)==1)
{
if(medianPos == count)
{
medianVal = readVal;
}
if ((medianPos += 1) == count)
{
if(size % 2) //This means that it is even
{
}
else
{
medianVal += readVal;
medianVal /= 2;
}
}
count++;
}
return medianVal;
}
File
1 1 2 3
5 8 13 21
34 55 89 144
233 377 610 987
1597 2584 4181 6765
Output
The Fibonacci median: -1576638118
Function Call
median = findMedian(Fibonacci, size);
Your 'count' variable is not initialized. So it is possible that your if conditions will not be met and your medianVal remain uninitialized too.
Related
I have to complete the function prime in order to the function main generate all prime numbers in a range specified by the user, but when I run the code specifying 1 as minimum and 100 as maximum it returns 1 with all the prime numbers.
How can I get rid of 1, once, by definition, 1 is not a prime number?
#include <cs50.h>
#include <stdio.h>
bool prime(int number);
int main(void)
{
int min;
do
{
min = get_int("Minimum: ");
}
while (min < 1);
int max;
do
{
max = get_int("Maximum: ");
}
while (min >= max);
for (int i = min; i <= max; i++)
{
if (prime(i))
{
printf("%i\n", i);
}
}
}
bool prime(int number)
{
// TODO
int j;
for (j = 2; j <= number - 1; j++)
{
if (number % j == 0)
{
return false;
}
}
return number;
}
Minimum: 1
Maximum: 100
1
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
I would say that the simplest solution would be to add a test at the beginning of your prime function to indicate that any value less than "2" would yield a "false" Boolean value. With that, here is a simple refactoring of the function.
bool prime(int number)
{
// TODO
if (number < 2) /* Exit gracefully if a minimum value of 1 or less is entered */
{
return false;
}
int j;
for (j = 2; j <= number - 1; j++)
{
if (number % j == 0)
{
return false;
}
}
return true; /* Technically returning a value greater than zero will equate to true, but it is better to return "true" */
}
Also, note the revision of the final return statement in the function. Technically, any integer value greater than zero will be treated as a Boolean "true" value, it would be best to return the Boolean "true" value there so to be clear to anyone reading the code.
See if that meets the spirit of your project.
I am learning c and encountered maximum cost path question in which
Rules:
matrix is n x n size
Starting from the cell (bottommost leftmost cell), you want to go to the topmost
rightmost cell in a sequence of steps. In each step, you can go either right or up from
your current location.
I tried to solve using dynamic programming and this is the function I have written
computecost(int *utr,int n)//utr is the input matrix
{
int *str;
int i,j;
str=(int *)malloc(n*n*sizeof(int));
for(j=0;j<n;j++)//intialization of bottom row
{
str[n*(n-1)+j]=utr[n*(n-1)+j];
}
for(i=n-2;i>=0;i--)
{
for(j=0;j<n;j++)
{
str[n*i+j]=utr[n*i+j]+max(str[n*(i+1)+j],str[n*(i+1)+(j+1)]);
}
}
printf("%d",str[n*0+0]);
return 0;
}
and this is the input
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&str[n*i+j]);
}
}
but
for the matrix 5 x5
1 4 8 2 9
32 67 18 42 1
4 86 12 7 1
8 4 12 17 44
1 43 11 45 2
the desired output is 272 but I am getting 211.
the output matrix for my case
1 43 11 45 2
51 47 57 62 46
55 143 74 69 47
175 210 92 111 52
211 214 119 113 64
Can anyone help me?
You don't need dynamic programming for this since there are no overlapping sub-problems. Just use a simple recursion.
const int n = 5;
int mat[n][n] = {
{1,4,8,2,9},
{32,67,18,42,1},
{4,86,12,7,1},
{8,4,12,17,44},
{1,43,11,45,2}
}; // input matrix
int f(int x, int y, int sum){
if(x == 0 && y == 4)
return sum;
int p = 0, q = 0;
if(x - 1 >= 0)
p = f(x-1, y, sum + mat[x-1][y]);
if(y + 1 <= 4)
q = f(x, y+1, sum+mat[x][y+1]);
return max(p,q);
}
int main(){
int maxSum = f(4,0, mat[4][0]);
printf("%d\n", maxSum);
}
You were not very far to succeed.
In practice, you did not initialize correctly the bottom row.
Moreover, there was a little mistake in the iteration calculation.
This is the corrected code.
As said in a comment, it could be further simplified, by avoiding the use of a new array, simply updating the input array.
#include <stdio.h>
#include <stdlib.h>
int max (int a, int b) {
return (a > b) ? a : b;
}
int computecost(int *utr,int n) { //utr is the input matrix
int *str;
str = malloc (n*n*sizeof(int));
str[n*n - 1] = utr[n*n - 1];
for (int j = n-2; j >= 0; j--) { //intialization of bottom row {
str[n*(n-1)+j] = utr[n*(n-1)+j] + str[n*(n-1)+j+1]; // corrected
}
for (int i=n-2; i>=0; i--) {
str[n*i+n-1] = utr[n*i+n-1] + str[n*(i+1)+n-1];
for(int j = n-2; j >= 0; j--) {
str[n*i+j] = utr[n*i+j] + max(str[n*(i+1)+j],str[n*i + j+1]); // corrected
}
}
int cost = str[0];
free (str);
return cost;
}
int main() {
int A[25] = {
1,43,11,45,2,
8,4,12,17,44,
4,86,12,7,1,
32,67,18,42,1,
1,4,8,2,9
};
int ans = computecost (A, 5);
printf ("%d\n", ans);
return 0;
}
I am currently learning C and trying to solve a problem. I need to find all the prime numbers from 2 to 100, using arrays and loops.
I already know of a solution to this problem however I am having trouble finding the error in my code. This is my first time using StackOverflow so hopefully I commented everything properly :)
#include <stdio.h>
#include <stdlib.h>
int main(){
int prime_numbers[50] = {2,3}; //initializes the array which will be printed at the end
int counter = 1; //initializes the index of the last prime element in array
int checker = 0; //initializes a checker used to determine if the number is prime
for(int i = 5; i <= 100; i++) { //goes through numbers 5 to 100 as the first two primes are hard coded
for(int j = 0; j <= counter; j++){ //goes through array untill it reaches last prime using the before initialized counter
if(i % prime_numbers[j] != 0) { //check to see if a number that is being checked is not divisible by j'th element in array
checker++; //if so, checker is incremented
}
if(checker == counter + 1) { //check to see if number was not divisible by any prime in our array
checker = 0; //if so checker is reset to 0 for the next iteration
++counter; //counter is incremented as there is one more prime in our array
prime_numbers[counter] = i; //add inside array the found prime number
break; //break should not be necessary, however for some reason, it yields a different result when I don't put it in
} //most likely the error in the code. Need to find out why loop does not stop after second if is done
}
}
for(int g = 0; g <= 50; g++) { //prints out all the prime numbers in array
if(prime_numbers[g] != 0) {
printf("%d ", prime_numbers[g]);
}
}
return 0;
}
I expect the program to print all the prime numbers from 0 to 100 with spaces in between.
The program also finds numbers that are not prime. Its logic is a rather strange inversion. The candidate needs to be divisible by only one prime in the array. The reporting also breaks the array bounds.
The corrected code:
#include <stdio.h>
int main(void) { // correct function signature
int prime_numbers[50] = {2,3};
int counter = 1;
int checker; // initialise within each loop
for(int i = 5; i <= 100; i++){
checker = 0; // inintialise here
for(int j = 0; j <= counter; j++) {
if(i % prime_numbers[j] == 0) { // opposite test to yours
checker++; // flag a non-prime
break;
}
}
if(checker == 0) { // moved outside the loop
++counter;
prime_numbers[counter] = i;
}
}
for(int g = 0; g < 50; g++) { // corrected the bounds error
if(prime_numbers[g] != 0){
printf("%d ", prime_numbers[g]);
}
}
printf("\n"); // flush the output buffer
return 0;
}
Program output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
The reporting loop relies on the array being initialised to 0s and a better way would be
for(int j = 0; j <= counter; j++) {
printf("%d ", prime_numbers[j]);
}
printf("\n");
The following code works well.
int main()
{
int k=1,temp,j;
const int N_prime = 10000; // number of primes to be generated
int primes[N_prime]; // array to save primes
primes[0] = 2;
primes[1] = 3;
temp = 5;
while (k!=N_prime-1){ // generating only N_prime prime numbers
for (j = 0; j <= k && primes[j] * primes[j] <= temp; j++){
if (temp%primes[j] == 0){ // if temp%primes[j] == 0 then temp is divisible by
temp += 2; // a prime and is not a prime itself, therefore
break; // immediately break
}
else if (primes[j+1] * primes[j+1]>temp){ // if no such primes found, temp is prime,
primes[k + 1] = temp; // save it and increase the value for
k++; // next check
temp += 2;
}
}
}
for (int ind = 0; ind < N_prime; ind++) printf("%d\n",primes[ind]);
getch();
return 0;
}
with the output:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
211
223
227
229
233
239
241
251
257
263
269
271
277
281
283
293
307
311
313
317
331
337
347
349
353
359
367
373
379
383
389
397
401
409
419
421
431
433
439
443
449
457
461
463
467
479
487
491
499
503
509
521
523
541
As I noticed, your code generates all the odd numbers up to 100.
I want to find prime numbers with multithreading and using Sieve of E. function.I write some piece of codes. If the program will run, the user enter a max number and thread number. The program should create threads that given thread number. The program find all prime numbers until the max number. Each thread must check one prime number.
My program doesn't find prime numbers. I write checkPrime function and crossout functions for finding prime numbers efficiently. But it doesn't work. So, I can't check my threads work correctly or not. How can I implement checkPrime function?
There are 3 functions. crossout is for Sieve E. method. checkPrime is for checking is a number prime or not. worker is for thread's function. Each thread must check one prime number.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#define MAX_N 100000000
#define MAX_THREADS 25
// global values
int threadNumber;
int largestNumber;
int isPrime;
int nthreads, // number of threads (not counting main())
prime[MAX_N + 1],
n, // in the end, prime[i] = 1 if i prime, else 0
nextbase; // next sieve multiplier to be used
// lock for the shared variable nextbase
pthread_mutex_t nextbaselock = PTHREAD_MUTEX_INITIALIZER;
void crossout(int a) {
int i, j, check;
for (i = 2; i < largestNumber; i++)
prime[i] = 1;
for (i = a; i < largestNumber;)
if (prime[i])
for (j = i; i * j < largestNumber; j++)
prime[i * j] = 0;
}
int checkPrime(int a) {
int i;
for (i = 2; i <= a; ++i) {
if (a % i == 0) {
isPrime = 1;
return isPrime;
break;
} else
isPrime = 2;
crossout(a);
return isPrime;
}
}
void* workerThread(void* t) {
int lim, base;
long i, j;
long tid;
tid = (long)t;
printf("Thread %ld starting...\n", tid);
while (1) {
pthread_mutex_lock(&nextbaselock);
base = nextbase;
nextbase++;
// unlock the lock
pthread_mutex_unlock(&nextbaselock);
if (base <= lim) {
if (prime[base]) {
checkPrime(base);
// log work done by this thread
}
}
if (checkPrime(base) == 2)
printf("Thread %ld done. Prime = %d\n", tid, base);
pthread_exit((void*) t);
}
return NULL;
}
//main function with two parameters :argc and argv
int main(int argc, char** argv) {
threadNumber = argv[3];
largestNumber = argv[1];
int i;
pthread_t thread[threadNumber];
int rc;
long t;
void* status;
for (t = 0; t < threadNumber; t++) {
printf("Main: creating thread %ld\n", t);
rc = pthread_create(&thread[t], NULL, workerThread, (void*)t);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
for (t = 0; t < threadNumber; t++) {
rc = pthread_join(thread[t], (void*)&t);
if (rc) {
printf("ERROR; return code from pthread_join() is %d\n", rc);
exit(-1);
}
printf("Main: completed join with thread %ld \n", t);
}
}
You are trying to mix two different methods for finding prime numbers. You don't need to use both the iterative division method and the sieve of Eratosthenes. This shows a way of implementing the sieve. Even numbers are ignored in the sieve but treated as special cases in isprime(). But it won't help you find a multi threaded solution, because you can't just hand over different numbers to different threads - each prime builds on the work of the previous prime, starting with the assumption that 3 is prime.
// Sieve of Eratosthenes
#include <stdio.h>
#include <stdlib.h>
#define LIMIT 200
char sieve[LIMIT] = { 1, 1, }; // 1 for not-prime
int isprime(unsigned n)
{
if(n <= 2) // special cases
return sieve[n] == 0;
if(n % 2 == 0) // even numbers are not prime
return 0;
if(n >= LIMIT) // test range
exit(1);
return sieve[n] == 0;
}
int main(void)
{
unsigned n, p;
for(n=3; n<LIMIT; n+=2) { // odd numbers only
if (sieve[n] == 0) { // if n is prime
for(p=n*n; p<LIMIT; p+=n*2) { // ignore even numbers
sieve[p] = 1; // not primne
}
}
}
printf("Prime numbers are:\n");
for(n=0; n<LIMIT; n++) { // check all numbers
if (isprime(n)) { // if n is prime
printf("%-4d", n);
}
}
printf("\n");
return 0;
}
Program output:
Prime numbers are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199
I'll now show an iterative division method. Once again, even numbers are treated as special cases. I don't often write multi threaded C code, so I can't help you with that. But I hope you can build on this second example to make a multi threaded solution.
// iterative division
#include <stdio.h>
#include <math.h>
#define LIMIT 200
int isprime(unsigned n)
{
unsigned s, i;
if(n <= 1)
return 0;
if(n == 2)
return 1;
if(n % 2 == 0) // no even numbers
return 0;
s = (unsigned)sqrt(n); // limit the loop
for(i=3; i<=s; i+=2) // odd numbers only
if (n % i == 0)
return 0;
return 1;
}
int main(void)
{
unsigned n;
printf("Prime numbers are:\n");
for(n=0; n<LIMIT; n++) { // check all numbers
if (isprime(n)) { // if n is prime
printf("%-4d", n);
}
}
printf("\n");
return 0;
}
Program output:
Prime numbers are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199
There are some pitfalls in both of the above examples when working with larger numbers, but I'll leave them for you to discover.
This is modified version of Sieve of Eratosthenes which is the very simple, interesting and fast. Understand its working as I have tried to explain it using comments. Actually try to understand the run-time allocation of array size to avoid defining a large MAX value and try to code simple by analyzing your algorithm and applying good mathematics along with smart coding knowledge.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
int *arr;
int count=0,i=3,j,n;
arr=(int*)malloc(count+1*sizeof(int)); //set array size to 1
arr[count++]=2; //stored 2 as array first element
printf("Find all prime numbers upto :: ");
scanf("%d",&n); //n is the number up to which prime numbers are required
here:
{
while(i<=n) //start with i=3
{
j=0;
while(arr[j]<=sqrt(i)) //till array element value is less than or equal to root of number under checking
{
if(i%arr[j]!=0) //if remainder is not zero check divisibility with next array element
j++;
else
{
i++; //if remainder is zero then start checking for another number
goto here;
}
}
printf("%d, ",arr[count-1]); //printing the number which was proved as prime last time
arr=(int *)realloc(arr,(count+1)*sizeof(int)); //increasing array size by 1
arr[count++]=i; //newly proved prime is stored as next array element
i++;
}
printf("%d, ",arr[count-1]); //print last number proved as prime
}
I'm trying to make a calculator for very big numbers (even bigger than long long) and I'm using arrays to make it work.
So far I have done addition, subtraction and multiplication. But I'm really stuck in division part.
EDIT:
new progress. as a friend mentioned i need to compare result array with divisor each time so i can stop the progress any time divisor is larger than dividend. I managed to make a nice function to compare it every time. this function is tested separately and it's working fine. OK. now i'm starting to make REAL progress. i got the quotient. now i will try to put quotient in array so that we can work with LARGER numbers!
#define MAX_SIZE 50
#define SIZE_USE (MAX_SIZE-1)
int div(int inum_first[], int inum_second[], int div_result[], int firstlen, int secondlen)
{
int i;
int check1 = 0, check2 = 0;
int zeroC = 0;
int tmp[MAX_SIZE];
for (i = 0; i <= SIZE_USE; i++)
{
tmp[i] = 0;
}
int inum_firstCP[MAX_SIZE] = { 0 };
for (i = 0; i <= 1; i++)
{
inum_firstCP[i] = inum_first[i]; // create a copy of inum_first
}
for (i = 0; i <= SIZE_USE; i++)
{
if (inum_first[i] != 0)
check1++;
if (inum_second[i] != 0)
check2++;
}
if (secondlen > firstlen)
{
zeroC++;
goto EOI;
}
if (check2 == 0)
{
puts("\nExpected error\n");
return -1;
}
int j = 0, p = 0;
int s = 0;
int o = 1; // o is Quotient!
do
{
for (i = SIZE_USE; i >= 0; i--)
{
if (tmp[i] = inum_firstCP[i] - inum_second[i] >= 0)
{
tmp[i] = inum_firstCP[i] - inum_second[i];
}
else
{
inum_firstCP[i - 1] = inum_firstCP[i - 1] - 1;
tmp[i] = (inum_firstCP[i] + 10) - inum_second[i];
}
inum_firstCP[i] = tmp[i];
}
if (compare(inum_firstCP, inum_second, firstlen, secondlen) < 0) break;
j++;
o++;
} while (j<MAX_SIZE); // anything else will also work
EOI:
return 0;
}
int compare(int inum_firstCP[], int inum_second[], int firstlen, int secondlen)
{
int c = 0, d = 0;
int i;
firstlen = MAX_SIZE, secondlen = MAX_SIZE; // temporary. will provide a better solution ASAP
if (firstlen > secondlen)
{
return 1;
}
else if (secondlen > firstlen)
{
return -1;
}
else
{
for (i = 0; i < firstlen; i++)
{
if (inum_firstCP[i] > inum_second[i]) c++;
else if (inum_second[i] > inum_firstCP[i]) d++;
}
if (c>d) return 1;
else if (d>c) return -1;
}
return 0; // else
}
If you have the subtraction of those big numbers the easiest solution is to take the two numbers and substract one from the other until you are left with something less then zero. It is the basic solution, it works but is a bit slow.
To make it faster you can do the following, take the divisor, multiply it by 2, if it is less then the dividend, keep on multiplying. When you will reach the first number bigger then a dividend set the corresponding bit to 1, subtract the multiplied dividend then do the same for the result.
There is the same thing nicely described on wiki.
In order to make it work you need to implement your own comparing function.
Assuming you will store the size of the malloc allocation in your structure in filed len you can do something like this:
int compare( mynum &a, mynum &b){
if (a.len() > b.len()){
return 1;
} else (if b.len() > a.len()){
return -1;
} else(){
for(int i = b.len(); i > 0; i--){
if (a[i] > b[i]){
return 1;
} else if(b[i] > a[i]){
return -1;
}
}
#if we get there the numbers are the same
return 0;
}
}
I've done this before and was very happy to implement it the same way as you'd do it by hand, with a small modification of multiple subtraction at each step. The algorithm is like that:
Multiply divisor by ten as often as you can without divisor becoming bigger than dividend.
Subtract divisor from dividend as often as you can and remember how many times.
The rest of all the subtractions is the new dividend.
Repeat at step (1) until dividend is smaller than divisor.
The current dividend is the "rest".
All the numbers remembered at step (3) are the "result" when ordered left to right (left calculated first).
Okay, let's try it by example:
E.g. you have 25391 and want to divide it by 71.
(1) 25391 and 71 * 10 = 710
25391 and 710 * 10 = 7100
25391 and 7100 * 10 = 71000 <-- TOO BIG
(2) 25391 - 7100 => X
18291 - 7100 => X
11191 - 7100 => X
4091 - 7100 <--- NOT POSSIBLE
(3) Number of X: 3
(4) 4091 > 71, okay, back to step 1.
(1) 4091 and 71 * 10 = 710
4091 and 710 * 10 = 7100 <--- TOO BIG
(2) 4091 - 710 => X
3381 - 710 => X
2671 - 710 => X
1961 - 710 => X
1251 - 710 => X
541 - 710 <--- NOT POSSIBLE
(3) Number of X: 5
(4) 541 > 71, okay, back to step 1
(1) 541 and 71 * 10 = 710 <--- TOO BIG
(2) 541 - 71 => X
470 - 71 => X
399 - 71 => X
328 - 71 => X
257 - 71 => X
186 - 71 => X
115 - 71 => X
44 - 71 <--- NOT POSSIBLE
(3) Number of X: 7
(4) 44 > 71, WRONG, continue with step 5
(5) Rest is 44
(6) Result is 357
If you had just tested how often you can subtract 71 from 25391, this loop would have had 357 iterations! Of course, my solution uses multiplication, but honestly, multiplying by 10 is no real multiplication, just shift all digits one position to the left and put a zero at the top right one.
The algorithm will need as many iterations as the result has digits and it will need at most 9 iterations (with subtraction) per digit.
#Mecki Try with 54 664 455 645 655 divided by 5 465 126 544, it fails. At step 3 you must add a number of '0' corresponding to the difference of length between the divisor (x n x 10) and the "rest". ie if the rest is 13 190 205 655 (11 digits length) and divisor is 54 651 265 440 000 (14 digits length) then three '0' must be added to the result before performing the next loop.