Calculating a catalan number in C - c

I'm struggling with some code I have to write for an assignment in C. I have to calculate a Catalan number recursively.
The following formula is given:
Formula IMG.
The awnsers should be:
0 > 1 (Filling in 0 should print 1)
5 > 42 (Filling in 5 should print 42)
7 > 429 (Filling in 7 should print 429)
9 > 4862 (Filling in 9 should print 4862)
10 > 16796 (Filling in 10 should print 16796)
Please have a look at it:
#pragma warning(disable : 4996)
#include <stdio.h>
int catalanRecursief(int n) {
if (n == 0){
return 1;
} else {
return (2 * ((2 * n) - 1)) / (n + 1) * (catalanRecursief(n - 1));
}
}
int main(void){
int n;
printf("Catalan printer\n\n");
printf("What catalan number do you want to calculate? ");
scanf("%d", &n);
/*catalanRecursief(n);*/
printf("Catalan number: %d > %d", n, catalanRecursief(n));
getchar();
return(0);
}

By changing the unit from n to float it will be enough to solve it.
int catalanRecursief(float n) {
if (n == 0) {
return 1;
} else {
return ((2 * ((2 * n) - 1)) / (n + 1)) * (catalanRecursief(n - 1));
}
}
or also
int catalanRecursief(int n) {
if (n == 0) {
return 1;
} else {
return ((2.0 * ((2 * n) - 1)) / (n + 1)) * (catalanRecursief(n - 1));
}
}
this is because dividing int numbers c truncates them

As the theory says that Catalan numbers are integers, you should just ensure that the division happens last to avoid an integer division truncation:
...
else {
return (2 * ((2 * n) - 1)) * (catalanRecursief(n - 1)) / (n + 1);
}
...
With 32 bits integers, overflow is to be expected starting at C17, so use long long if you want to go further...

Related

A function that takes an integer and inserts zeros between its digits

The function should take the address of the integer and modify it by inserting zeros between its digits. For example:
insert_zeros(3) //3
insert_zeros(39) //309
insert_zeros(397) //30907
insert_zeros(3976) //3090706
insert_zeros(39765) //309070605
My code:
#include <stdio.h>
#include <math.h>
void insert_zeros(int* num);
int main() {
int num;
printf("Enter a number:");
scanf("%d", num);
insert_zeros(&num);
printf("Number after inserting zeros: %d", num);
return 0;
}
void insert_zeros(int* num){
int count = 0;
int tmp = *num;
//Count the number of digits in the number
while(tmp != 0){
tmp /= 10;
count++;
}
//calculating the coefficient by which I will divide the number to get its digits one by one
int divider = (int)pow(10, count-1);
int multiplier;
tmp = *num;
*num = 0;
/*
The point at which I'm stuck
Here I tried to calculate the degree for the number 10
(my thought process and calculations are provided below)
*/
(count >= 3)? count += (count/2): count;
//the main loop of assembling the required number
while (count >= 0){
multiplier = (int)pow(10, count); //calculating a multiplier
*num += (tmp / divider) * multiplier; //assembling the required number
tmp %= divider; //removing the first digit of the number
divider /= 10; //decreasing divider
count -= 2; //decreasing the counter,
//which is also a power of the multiplier (witch is 10)
}
}
My idea consists of the following formula:
For number "3" I shold get "30" and it will be:
30 = (3 * 10^1) - the power is a counter for number "3" that equals 1.
For number "39" it will be "309":
309 = (3 * 10^2) + (9 * 10^1)
For number "397" it will be "30907":
30907 = (3 * 10^4) + (9 * 10^2) + (7 * 10^0)
For number "3976" it will be "3090706":
3090706 = (3 * 10^6) + (9 * 10^4) + (7 * 10^2) + (6 * 10^0) - with each iteration power is decreasing by 2
For number "39765" it will be "309070605":
309070605 = (3 * 10^8) + (9 * 10^6) + (7 * 10^4) + (6 * 10^2) + (5 * 10^0)
And so on...
For a 3-digit number, the start power should be 4, for a 4-digit number power should be 6, for a 5-digit it should be 8, for 6-digit it should be 10, etc.
That algorithm works until it takes a 5-digit number. It outputs a number like "30907060" with an extra "0" at the end.
And the main problem is in that piece of code (count >= 3)? count += (count/2): count;, where I tried to calculate the right power for the first iterating through the loop. It should give the right number to which will be added all the following numbers. But it only works until it gets a 5-digit number.
To be honest, so far I don't really understand how it can be realized. I would be very grateful if someone could explain how this can be done.
As noted in comments, your use of scanf is incorrect. You need to pass a pointer as the second argument.
#include <stdio.h>
#include <math.h>
int main(void) {
int num;
scanf("%d", &num);
int num2 = 0;
int power = 0;
while (num > 0) {
num2 += (num % 10) * (int)pow(10, power);
num /= 10;
power += 2;
}
printf("%d\n", num2);
return 0;
}
There's an easy recursive formula for inserting zeros: IZ(n) = 100*IZ(n/10) + n%10.
That gives a very concise solution -- here the test cases are more code than the actual function itself.
#include <stdio.h>
#include <stdint.h>
uint64_t insert_zeros(uint64_t n) {
return n ? (100 * insert_zeros(n / 10) + n % 10) : 0;
}
int main(int argc, char **argv) {
int tc[] = {1, 12, 123, 9854, 12345, 123450};
for (int i = 0; i < sizeof(tc)/sizeof(*tc); i++) {
printf("%d -> %lu\n", tc[i], insert_zeros(tc[i]));
}
}
Output:
1 -> 1
12 -> 102
123 -> 10203
9854 -> 9080504
12345 -> 102030405
123450 -> 10203040500
Adapting some code just posted for another of these silly exercises:
int main() {
int v1 = 12345; // I don't like rekeying data. Here's the 'seed' value.
printf( "Using %d as input\n", v1 );
int stack[8] = { 0 }, spCnt = -1;
// Peel off each 'digit' right-to-left, pushing onto a stack
while( v1 )
stack[ ++spCnt ] = v1%10, v1 /= 10;
if( spCnt == 0 ) // Special case for single digit seed.
v1 = stack[ spCnt ] * 10;
else
// multiply value sofar by 100, and add next digit popped from stack.
while( spCnt >= 0 )
v1 = v1 * 100 + stack[ spCnt-- ];
printf( "%d\n", v1 );
return 0;
}
There's a ceiling to how big a decimal value can be stored in an int. If you want to start to play with strings of digits, that is another matter entirely.
EDIT: If this were in Java, this would be a solution, but the problem is in C, which I'm not sure if this can convert to C.
This may be a lot easier if you first convert the integer to a string, then use a for loop to add the zeros, then afterward reconvert to an integer. Example:
int insert_zeros(int num) {
String numString = Integer.toString(num);
String newString = "";
int numStringLength = numString.length();
for (int i = 0; i < numStringLength; i++) {
newString += numString[i];
// Only add a 0 if it's not the last digit (with exception of 1st digit)
if (i < numStringLength - 1 || i == 0) newString += '0';
}
return Integer.parseInt(newString);
}
I think this should give you your desired effect. It's been a little bit since I've worked with Java (I'm currently doing JavaScript), so I hope there's no syntax errors, but the logic should all be correct.

I need made a combinatorial analysis on an array and generate a number with this

Hi i am an amateur in programing, but i propose me to getting better and because that i start to solve problems in online judges and i don't know how to do a combinatorial analysis, i found some similar question but i can't apply to my code, if you are able to explain me how to do it, i will be incredibly grateful.
so here is the full text of the problem, translated of Portuguese to English. At end is my code.
To prove her scientific skills Princess Bubblegum learned to program using BMO (The best computer in the Candy kingdom) and like every programmer she fell in love with binary numbers.
Because of her addiction to binary numbers she loves decimal numbers that look like a binary number (i.e. a decimal number that contains only digits 0 and 1, for example 101) so given a decimal number N she wants to find a multiple of that number that looks like a number binary, but for some numbers it was taking a long time to find that multiple, even with the help of BMO. Because of her problem-solving addiction, she wasn't doing anything until she found this multiple. Perfect situation for the Earl of Lemongrab, who has taken over the Candy Kingdom. As Finn and Jake, the heroes of the Candy kingdom, can't do anything against the Count and know nothing about multiples, they asked to find the multiples and thus save the kingdom.
Prohibited
The input contains up to 2*10^5 lines, each line with an integer N (0 < N < 10^12), the number Princess Bubblegum wants to find the multiple M (M != 0), this number must be smaller than 10^12, otherwise it doesn't fit in the BMO architecture.
Exit
Print a single integer per line, if there are multiple multiples print the smallest one. If there is no solution print -1
#include <stdlib.h>
#include <math.h>
int main() // normal ways works fine but i have to do it faster, time limit is 2s//
//doing 11 fors works to but its have same tle problem//
{
long long int n, R, num, res, expo;
int b = 0, dig[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, E=0, an, anmax = 1024, reseter, cob, casa;
while (E < 200000)
{
E++;
num = 0;
scanf("%lld", &n); //I have to read a decimal number and from that found the smaller multiple number that is similar to a binary number, and cannot be 0//
res=n%10;
if ((res==1) || (res==0)) // in case the read number is already similar to binary, this works fine//
{ b=1;
for ( num=n;((num>0) && (b==1)); num=num/10)
{
res=num%10;
if ((res==1) || (res==0)){
b=1;
R=n;
}else
{
b=0;
R=-1;
}
}
}else{
if ((n > 0) && (n < 1000000000000))
{
if (n < 500000000000)
{
num = n;
for (expo = -1; num >= 1; expo++, num = num / 10)//so expo is a varieble to found the smaller house of input to made a number, its just for reduce cycles//
{
res = num % 10;
}
if (res > 1)
{
expo = expo + 1;
}
dig[expo] = 1;
R = ((dig[11] * 100000000000) + (dig[10] * 10000000000) + (dig[9] * 1000000000) + (dig[8] * 100000000) + (dig[7] * 10000000) + (dig[6] * 1000000) + (dig[5] * 100000) + (dig[4] * 10000) + (dig[3] * 1000) + (dig[2] * 100) + (dig[1] * 10) + (dig[0] * 1));
for (dig[expo] = 1; ((expo < 11) && (b == 0)); expo++)//// 1 is fixed value until no one of numbers is divisible//
{
anmax = pow(2, expo);//forget this line//
dig[expo] = 1;
for (casa = 0; ((casa < expo) && (b == 0)); casa++)//here is my problem i dont know how to alternate all values that can be ninary//
{ //this is my original idea to solve but this don't generate all possible values//
for (cob = 0; ((cob < 2) && (b == 0)); cob++)
{
dig[casa] = cob;
R = ((dig[11] * 100000000000) + (dig[10] * 10000000000) + (dig[9] * 1000000000) + (dig[8] * 100000000) + (dig[7] * 10000000) + (dig[6] * 1000000) + (dig[5] * 100000) + (dig[4] * 10000) + (dig[3] * 1000) + (dig[2] * 100) + (dig[1] * 10) + (dig[0] * 1));
if ((R % n) == 0)
{
b = 1;
}
}
}
if ((cob == 2) || (b==1))
{
for (reseter = expo; reseter >= 0; reseter--)//it works fine is just to start all values with 0 before its repeats//
{
dig[reseter] = 0;
}
}
}
}
else
{
R = -1;
}
if((R==11111111111) && ((n!=21649) || (n!=513239))){
R=-1; //its not important//
}
}else
{
R=-1;
}
}
// reset para proximos valores//
b = 0;
printf("%lld\n", R);
}
return 0;
}

Prime factorization of larger numbers than int

This program does Prime Factorization Of Numbers In C.
#include <stdio.h>
int main(void) {
int number, i, p, n, factors, count;
int numbers[1000000];
int counter = 0;
char text[100000];
for (count = 0; count < 1000000; count++) {
fgets(text, 10000000, stdin);
if (sscanf(text, "%d", &number) == 1) {
if (number == 0)
break;
numbers[count] = number;
} else {
numbers[count] = 0;
}
}
counter = 0;
for (i = 0; i < count; i++) {
if ((numbers[i] < 0) || (numbers[i] == 0)) {
fprintf(stderr, "Error: Wrong Input!\n");
return 100;
break;
}
number = numbers[i];
printf("Prime factorization of nubmer %d is:\n", number);
factors = 0;
for (p = 2; p * p <= number; p += 1 + (p & 1)) {
if (number % p == 0) {
n = 0;
factors++;
do {
number /= p;
n++;
} while (number % p == 0);
if (n == 1) {
printf("%d ", p);
++counter;
} else
printf("%d^%d ", p, n);
++counter;
if (count > 0 && number != 1)
printf("x ");
}
}
if (factors == 0 || number != 1)
printf("%d", number);
printf("\n");
}
return 0;
}
This program works fine for numbers smaller than 108. But my question is, if there is a way to make this program even for numbers like 1012. I know that int would not be enough, but when I tried for example long int, it didn't worked. Also I heard something about malloc, but I keep failing to implement (understand) it.
Factorising large numbers usually needs a more subtle approach than simple trial division. Here is a possible outline method:
Make a list of all the primes up to, say, 25,000.
Use the list to remove all prime factors below 25,000.
If there is a remainder > 1 then check if the remainder is prime with a Miller-Rabin test or similar.
If the remainder is prime, then you have found the last factor.
If the remainder is not prime, then you are going to have to factorise it. That will inevitably be slow I'm afraid.
You can use long long. But probably, the real problem is, that it will take a veeeeerrrryyy long time to do the factorization on numbers, that don't fit in a normal int. E.g. you're trying to factorize a prime number in the range 10^12, then you will have to do about 10^6 divisions.
The thing about malloc won't help you with this problem at all, because even bigger values will take even longer to factorize. So, if you want to know, how malloc works, I suggest opening a separate question for that.
Below is a rework of the code using unsigned long long. (I tossed the file stuff to keep this to a minimal example.) Whether this works for your purpose depends on how your system defines a long long (on my system it's 64 bits). I also redid the output format to be compatible with the Unix dc command's postfix notation so I could easily check if the results were correct:
#include <stdio.h>
#include <stdlib.h>
int main() {
unsigned long long large = 18446744073709551615ULL; // 2^64 - 1
for (unsigned long long counter = large - 1000; counter < large; counter++) {
unsigned long long number = counter;
printf("Prime factorization of %llu is:", number);
unsigned long factors = 0;
for (unsigned long long p = 2; p * p <= number; p += 1 + (p & 1)) {
if (number % p == 0) {
factors++;
unsigned long n = 0;
do {
number /= p;
n++;
} while (number % p == 0);
if (n == 1) {
printf(" %llu", p);
}
else {
printf(" %llu %lu ^", p, n);
}
if (number != 1 && factors > 1) {
printf(" *");
}
}
}
if (factors == 0 || number != 1) {
factors++;
printf(" %llu", number);
}
if (factors > 1) {
printf(" *");
}
printf("\n");
}
return 0;
}
SAMPLE OUTPUT
% ./a.out
Prime factorization of 18446744073709550615 is: 5 563 * 751 * 8725722280871 *
Prime factorization of 18446744073709550616 is: 2 3 ^ 3 * 41 * 7523 * 8243 * 14479 * 20879 *
Prime factorization of 18446744073709550617 is: 79 557 * 419215600611539 *
Prime factorization of 18446744073709550618 is: 2 2298974999 * 4011949691 *
Prime factorization of 18446744073709550619 is: 3 3 ^ 1008659 * 677347590683 *
Prime factorization of 18446744073709550620 is: 2 2 ^ 5 * 7 * 149 * 233 * 3795329598449 *
Prime factorization of 18446744073709550621 is: 11 23 * 72912031911895457 *
Prime factorization of 18446744073709550622 is: 2 3 * 479909 * 6406334004193 *
Prime factorization of 18446744073709550623 is: 3421377637 5391612979 *
Prime factorization of 18446744073709550624 is: 2 5 ^ 61 * 593 * 1699 * 9379762391 *
Prime factorization of 18446744073709550625 is: 3 5 4 ^ * 13 * 756789500459879 *
Prime factorization of 18446744073709550626 is: 2 3743461 * 2463862195133 *
Prime factorization of 18446744073709550627 is: 7 1283 * 4339 * 627089 * 754877 *
Prime factorization of 18446744073709550628 is: 2 2 ^ 3 2 ^ * 101 * 293 * 42751 * 405025111 *
Prime factorization of 18446744073709550629 is: 17 43 * 613 * 66457 * 619442699 *
...
This runs slower but reasonably. You can push this further on some systems by swapping unsigned long long for a uint128_t which some compilers support somewhat:
typedef unsigned __int128 uint128_t;
(And up the unsigned long declarations to unsigned long long.) You'd need to supply number printing routines for the uint128_t type as printf() isn't going to handle them directly. I tried this with the above code and it worked:
Prime factorization of 340282366920938463426481119284349108124 is: 2 2 ^ 31 * 6131 * 7654271 * 21163829 * 21491837 * 128562653437 *
% dc
2 2 ^ 31 * 6131 * 7654271 * 21163829 * 21491837 * 128562653437 * p
340282366920938463426481119284349108124
But I never saw it complete more than one number while running it!
Using type unsigned long long for number and the prime factors will take you to 1019 at the price of longer computation times.
Note however that defining a large local array with automatic storage may cause problems, especially when it reaches a size of 8 megabytes as would be the case for type unsigned long long (this type is at least 64-bit wide). Allocating it from the heap is safer.
Here is an adapted version of the code:
#include <stdio.h>
#include <stdlib.h>
#define NUMBER_MAX 1000000
int main(void) {
unsigned long long *numbers;
unsigned long long number, p;
int i, n, factors, count;
char text[100];
numbers = calloc(NUMBER_MAX, sizeof(*numbers));
if (numbers == NULL) {
printf("cannot allocate number array\n");
return 1;
}
for (count = 0; count < NUMBER_MAX; count++) {
if (!fgets(text, sizeof text, stdin)) {
break;
}
if (sscanf(text, "%llu", &number) == 1 && number > 0) {
numbers[count] = number;
} else {
fprintf(stderr, "Error: Wrong Input!\n");
return 100;
}
}
for (i = 0; i < count; i++) {
number = numbers[i];
printf("Prime factorization of nubmer %llu is:\n", number);
factors = 0;
for (p = 2; p < 0x100000000 && p * p <= number; p += 1 + (p & 1)) {
if (number % p == 0) {
n = 0;
factors++;
do {
number /= p;
n++;
} while (number % p == 0);
if (n == 1) {
printf("%llu ", p);
} else {
printf("%llu^%d ", p, n);
}
if (number != 1) {
printf("* ");
}
}
}
if (factors == 0 || number != 1) {
printf("%llu", number);
}
printf("\n");
}
free(numbers);
return 0;
}

C Program: Adding a series using recursion

I am new to recursion so I am trying to write a simple program that adds to the nth number of the series 1/n. So if the user enters n = 4, the program will add 1 + 1/2 + 1/3 + 1/4. My program keeps outputting that the sum of the series is 0. Can someone please explain what I am doing wrong? I'd appreciate the help. Here is my code:
#include <stdio.h>
double sum(double n);
int main() {
double n;
double total;
printf("Enter a positive integer greater than 0: ");
scanf("%lf", &n);
total = sum(n);
printf("Sum: %lf", total);
return 0;
}
double sum(double n) {
if (n == 1)
return 1;
else
return ((1 / n) + sum(n - 1));
}
The problem is in the definition of this function:
double sum(int n) {
if (n == 1)
return 1;
else
return ((1 / n) + sum(n - 1));
}
n is int so 1/n will be always evaluated as int since both 1 and n are integers. Thus 1/n is always 0 for each n>1.
The solution would be to define n as double :
double sum(double n) {
if (n <= 1.0)
return 1.0;
else
return ((1.0 / n) + sum(n - 1.0));
}
Check your base case. sum(1) should return 1.
Also, an int divided by an int returns an int. Use a floating point number in your division.
It should be
double sum(double n) {
if (n == 1)
return 1.0;
else
return ((1.0 / n) + sum(n - 1));
}
1/n will always return 0 since 'n' acts as an integer value and not a float value even though the datatype is double as the value assigned to it is of type integer.

How does recursive function in C works

Function fun(n) is defined as such:
fun(n) = 1 (if n <=1)
fun(n) = fun(n/2) (if n is even)
fun(n) = 2*fun((n-1)/3) (if n> and n is odd)
I'm trying to write a recursive function to compute and return the result. I just started learning recursion, I got kind of lost while doing this function. Can someone correct me and explain to me? Thanks!
Here's what I did:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int fun(int n);
int main()
{
int num;
printf("\nEnter a number: ");
scanf("%d", num);
printf("Result = %d\n", fun(num));
return 0;
}
int fun(int n)
{
if (n <= 1)
{
return 1;
}
else if (n % 2 == 0)
{
return fun(n / 2);
}
else if ((n > 1) && (n % 2 == 0))
{
return 2 * fun((n - 1) / 3);
}
}
Expected output:
Enter a number: 13
Result = 2
Enter a number: 34
Result = 4
Output I'm getting instead:
Enter a number: 13
Result = 1
Enter a number: 34
Result = 1
scanf takes a pointer to int as argument for %d, i.e.,
scanf("%d", &num);
Also, your function fun does not handle all cases and may fall off the bottom:
if (n <= 1)
{
return 1;
}
else if (n % 2 == 0)
{
return fun(n / 2);
}
else if ((n > 1) && (n % 2 == 0))
{
return 2 * fun((n - 1) / 3);
}
The last else if condition is never met, because the previous check for n % 2 == 0 already returns in that case. Also the n > 1 is pointless because the first n <= 1 returns in all other cases.
You can simply make it:
else
{
return 2 * fun((n - 1) / 3);
}
The culprit is the last else if condition. Change it to:
else if ((n % 2) != 0)
The condition that n is odd is written wrong here. You wrote the same thing as for when n is even.
Its probably better to explicitly make the cases disjoint so you always return and there's no warning, like this:
int fun(int n)
{
if(n <= 1)
return 1;
if(n % 2 == 0)
return fun(n/2);
//No need for a condition, we know the last one must be satisfied
return 2 * fun((n-1)/3);
}
or, add another "default" case that indicates there was some error.
I think last if should be:
else if ((n > 1) && (n % 2 != 0))
Notice the != instead of ==.
The third condition
else if ((n > 1) && (n % 2 == 0))
is wrong, but instead of fixing it just you else no else if - because all other conditions were checked already.

Resources