Codechef/SPOJ : 'Marbles' Runtime Error - c

I've tried the Marbles pkroblem on spoj - (link: http://www.spoj.com/problems/MARBLES/ )
However I'm getting Runtime Error(SIGSEGV) after multiple tries.
Here's the code I submitted -
#include <stdio.h>
int comb(long int n, long int k)
{
if (n==k || k==0)
return 1;
else
return (comb(n-1, k) + comb(n-1, k-1));
}
int main() {
int t;
long int n, k;
scanf("%d", &t);
while(t--)
{
scanf("%ld %ld", &n, &k);
printf("%d\n", comb(n-1, k-1));
}
return 0;
}
I cant understand why I'm getting the error. Other solutions on the internet have all used iterative way to calculate the nCr combination. I've tried using a recursive approach. Any help would be highly appreciated.

you are decrementing n in the recursion but you don't check the case when n becomes 0 or negative, so the segfaul basically tells you that you get into an infinite recursion.
just add some stop criterion in addition to n==k || k==0.
I didn't look at the problem description so I don't know what the correct condition is, but perhaps you need something like
if (n==k || k==0 || n==0)

Related

Write a C function that takes a number as a parameter and returns 1 if it is prime, otherwise, it returns 0. It prints 1 for 23 and 0 for 22 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 months ago.
Improve this question
I just want a 1 or 0 if it is prime or not.
but I am getting multiple 0's and 1's. How can I solve this.
#include <stdio.h>
int num() {
int a, i;
printf("Enter a number:");
scanf("%d", &a);
for (i = 2; i < a; i++) {
if (a % i == 0)
printf("1");
else
printf("0");
}
}
int main() {
num();
return 0;
}
Based on the naming used and specific combination of function use, I am almost certain OP's code is based off this which is my first google response to c check if number is prime.
I challenged myself to "fix" it with least number of modification to the original code, here is the version that works the way OP expects. It is ugly but the point is to make it clear where it differs from his code.
OP seems to have mixed up the inner if statements with the outer if statements, and completely forgot about the counter. Also OP seems to have got confused in the function num, as it should either print 1 or 0 and be a void function, or return 1 or 0 and take a as input to a function that returns int eg int num(int a) or void num(), whereas OP ended up going halfway int num().
The working(if you can call it that, since fflush(stdout) is not called after printf is called, so the program will not not show the question on mingw without winpty) program would look like this:
#include <stdio.h>
void num() {
// a is the user input number
// c is the count
// i is the iterator
int a, i, c = 0;
printf("Enter a number: ");
scanf("%d", &a);
for (i = 2; i < a; i++) {
if (a % i == 0)
++c;
}
if (c != 0)
printf("0");
else
printf("1");
}
int main() {
num();
return 0;
}
The reason you get multiple 0s and 1s is you print them for every potential factor. You should instead test the factors to determine if none of the factors up to the square root of the number divide the number evenly, printing a 1 in this case and a 0 otherwise.
Function isprime should take an int argument and return 1 or 0, the main() function takes case of getting the number from the user and printing the result.
Here is a modified version:
#include <stdio.h>
int isprime(int a) {
int i;
if (a < 2)
return 0;
for (i = 2; a / i >= i; i++) {
if (a % i == 0)
return 0;
}
return 1;
}
int main() {
int a;
printf("Enter a number:");
if (scanf("%d", &a) == 1) {
printf("%d\n", isprime(a));
}
return 0;
}
Also note how the code is indented and uses spaces to improve readability. Learn how to do this for your next projects.

c program to calculate value of e^x, correct upto 10 decimal places

I am writing a program that calculates the value of e^x, according to the expansion formula.I need to print the answer so that it is correct upto 10 decimal places. I have tried to do it using, for, while and do while loop , however I cannot figure out where to terminate the loop , which condition to use to terminate the loop. i have written the code as follows:
#include<stdio.h>
#include<math.h>
int factorial(int x);
int main()
{
int x,n;
float sum,d_1;
printf("Enter the value of power :");
scanf("%d",&x);
n=1;sum=1;
while(sum <= %.10f)
{
d_1=pow(x,n)/factorial(n);
sum=sum+d_1;
n++;
}
printf("Answer is %f",sum);
return 0;
}
int factorial(int y)
{
int fact=1,i;
for(i=1;i<=y;i++)
{
fact=fact*i;
}
return(fact);
}
and i am getting the error message expected expression before %.
Please help.
You want to terminate the loop when the current term is smaller than some value. Also you want the loop to execute at least once, so a do-while loop is preferable:
n = -1;
do {
n++;
d_1 = pow(x, n) / factorial(n);
sum = sum + d_1;
} while (d_1 > epsilon);
As mentioned in the comments, there are other issues with the code when it comes to precision and overflow but that is a different story.

Having trouble with CS50 Greedy.c problem

I recently enrolled myself into the CS50 class offered by EDx.com. I'm currently having trouble with the greedy.c problem is pset1. I feel like the problem is that my do-while loops aren't actually looping. Regardless of the input I give the program I get 4 coins every time. Please let me know what I'm doing wrong.
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
int n = 0;
int count = 0;
int cents = 0;
do
{
printf("How much change is owed?\n");
get_int();
}
while(n > 0);
do
{
count++;
n -=25;
}
while(n >= 25);
do
{
count++;
n -=10;
}
while(n >= 10);
do
{
count++;
n -=5;
}
while(n >= 5);
do
{
count++;
n -=1;
}
while(n >=1);
printf("Here is %i coins\n", count);
}
This line in your code:
get_int();
Does nothing.
get_int will get and return an int, however you never actually put that value in a variable, that is the reason the input does not change the program's behavior.
Perhaps you meant to write something like this:
n = get_int();
The do while loops will always execute once that's why you're always getting 4 coins, then you're also not assigning the input value to n.
The first do while will run infinitely if n > 0 so change it to:
do {
printf("How much change is owed?\n");
n = get_int();
} while (n == 0);
next your do whiles will add to count even when they shouldn't, the below should be better.
while (n >= 25) {
count++;
n -= 25;
}
Good luck with CS50, thats where I started as well, it's difficult but really sets you up to learn to think.

Stack limit exceeded due to repeated recursion

This code is to print the Fibonacci series using recursion. So I thought to devise a recursion instead of using iteration but as soon as I just execute the code and as soon as the value provider function is executed it is showing some error "segmentation error". I want to do it this way only... Can anyone help? I'm just a beginner so please help and encourage me...
#include<stdio.h>
int fibonacci(int n)
{
int res;
if(n==0)
return 0;
if(n==1)
return 1;
else
res = fibonacci(n-1)+fibonacci(n-2);
return res;
}
int value_provider(int n)
{
int choice1;
if(n>=0)
{
choice1 = fibonacci(n-1);
n -- ;
}
printf("%d",choice1);
if(n>=0)
{
value_provider(n);
}
}
void main()
{
int n;
printf("enter the number");
scanf("%d",&n);
value_provider(n);
}
This code is showing segmentation fault...
What can I do to remove it rather than changing the code?
I want to do it only this way; please help!
I think your value_provider function has poor terminating conditions.
Don't try to calculate fibonacci of -1 so n must be >=1
Also once n is zero you need to finish the recursion, don't
call value_provider again.
Try something more like this;
int value_provider(int n)
{
int choice1=-1;
if(n>=1)
{
choice1 = fibonacci(n-1);
n -- ;
}
printf("%d ",choice1);
if(n>0)
{
value_provider(n);
}
}

Why is my CheckFactorial script not working? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
#include <stdio.h>
int checkiffactorial();
int factorial(int n);
int number;
int main()
{
int answer, n, i;
printf("Enter a number: ");
scanf("%d", &number);
answer = checkiffactorial();
if (answer == 1)
{
printf("It's a factorial");
}
else
{
printf("It's not a factorial");
}
}
int checkiffactorial()
{
static int whichnumber = 1;
int currnumber;
if (whichnumber > number)
{
return 0;
}
if(whichnumber <= number)
{
currnumber = factorial(whichnumber);
if (currnumber == factorial(number))
{
return 1;
}
whichnumber++;
checkiffactorial();
}
}
int factorial(int n)
{
int i;
int fac;
for(i=1; i<=n; ++i)
{
fac = fac * i;
}
}
Why is this code not working?
My C code is meant for you to input a number and check if that number can be a factorial.
Like for example: if you enter 6 it should be Yes because 3! = 6 but if you enter 8 it would not work.
I d'ont think it's a duplicate because the method i did it was different.
Please note i'm not really good at C so any extra tips could be appreciated.
You need to correct 3 mistakes to make this program work.
You're comparing factorial of whichnumber with factorial of number that's wrong.
currnumber = factorial(whichnumber);
if (currnumber == factorial(number)) //<----never be true
{
return 1;
}
You should compare factorial of whichnumber with number
currnumber = factorial(whichnumber);
if (currnumber == number) //<----should check whether it's same with the number
{
return 1;
}
2 . You should initialize fac variable in factorial function otherwise it will take some garbage value.
int fac=1; //<-----initialize this variable
3. You should return the value of fact after calculating the factorial.
return fac; //<-----should return value
Here is the modified code:
#include <stdio.h>
int checkiffactorial();
int factorial(int n);
int number;
int main()
{
int answer, n, i;
printf("Enter a number: ");
scanf("%d", &number);
answer = checkiffactorial();
if (answer == 1)
{
printf("It's a factorial");
}
else
{
printf("It's not a factorial");
}
}
int checkiffactorial()
{
static int whichnumber = 1;
int currnumber;
if (whichnumber > number)
{
return 0;
}
if(whichnumber <= number)
{
currnumber = factorial(whichnumber);
if (currnumber == number) //<----should check whether it's same with the number
{
return 1;
}
whichnumber++;
checkiffactorial();
}
}
int factorial(int n)
{
int i;
int fac=1; //<-----initialize this variable
for(i=1; i<=n; ++i)
{
fac = fac * i;
}
return fac; //<-----should return value
}
It has been pointed out to you that you don't return value from your functions and use uninitialsed values. These errors are easy to make, but they are also easy to catch: Enable warnings for your compiler and they will tell you about these things.
Suvojit's answer tells you what is wrong with your factorial function. Unfortunately, more things are wrong with your factorial check:
You make the number you check a global variable. This should really be an argument to the function, so that you can call it like you should: is_factorial(n).
You make your counter a static variable. This is like a global variable, but with the restriction that it is only known in this function, which means that you cannot change it from outside. If your program want to check several numbers, the second call starts where you left off earlier, which leads to wrong results.
Of course that's what you want in your implementation, because you use a recursive algorithm. In this case, that's not a good choice; use a loop.
Your condition when to stop the iteration (or when to break the loop) checks the number against the number you took the factorial of. You should test this against the factorial itself.
Note that a typical int has 32 bits and can represent positive values up to 2³¹. The factorial 13! already exceeds this limit. So you must check your number against 12 values.
You don't need the factorial function for this, you can build these values as you go, because n! = (n − 1)! · n. (You can use the factorial function, but will do the same calculations over and over again, which is wasteful. It doesn't matter for this toy problem, but it is worth bearing such things in mind.)
So here's your function, completely rewritten:
int is_factorial(int n)
{
int fact = 1;
int k = 1;
while (k < 13 && fact <= n) {
fact *= k;
if (n == fact) return k;
k++;
}
return 0;
}
It returns 0 when the n isn't a factorial, otherwise it returns the number that n is a factorial of. (This information is used anyway, so why not provide it? The caller can choose whether to use this infor or just use it as truth value.)
While we're at it, let's adjust the main function so that the program checks for bad input and prints out the extra information we return:
int main(void)
{
int n;
printf("Enter a number: ");
if (scanf("%d", &n) < 1) {
printf("Illegal input!\n");
} else {
int m = is_factorial(n);
if (m) {
printf("%d is the factorial of %d!\n", n, m);
} else {
printf("%d is not a factorial!\n", n);
}
}
return 0;
}
The things to take away here are that you should use the compiler warning to tell you about simple errors, that you should avoid global and static variables for closed problems like these and that loops are often simpler than recursion.

Resources