Pascal Triangle in C - c

So I implemented this Pascal Triangle program in C, and it works well up until the 13th line, where the values onwards are no longer correct. I believe the combination function is correct, a k combination of n elements can be written with factorials, and it says so on the combination Wikipedia page hehe. Here's the code:
#include <stdio.h>
int factorial(int number);
int combination(int n, int k);
int main() {
int lines;
int i, j;
printf("Number of Pascal Triangle lines: ");
scanf("%d", &lines);
for (i = 0; i <= lines; i++) {
for (j = 0; j <= i; j++)
printf("%d ", combination(i, j));
printf("\n");
}
}
int combination(int n, int k) {
int comb;
comb = (factorial(n)) / (factorial(k) * factorial(n - k));
return comb;
}
int factorial(int number) {
int factorial = 1;
int i;
for (i = 1; i <= number; i++)
factorial = factorial * i;
return factorial;
}

Computing Pascal's triangle straight from the binomial formula is a bad idea because
the computation of the factorial in the numerator is overflow-prone,
every computation requires the evaluation of about n products (k + n - k) and a division (plus n! computed once), for a total of n² per row.
A much more efficient solution is by means of Pascal's rule (every element is the sum of the two elements above it). If you store a row, the next row is obtained with just n additions. And this only overflows when the element value is too large to be representable.
In case you only need the n-th row, you can use the recurrence
C(n,k) = C(n,k-1).(n-k+1)/k
This involves 2n additions, n multiplications and n divisions, and can overflow even for representable values. Due to the high cost of divisions, for moderate n it is probably better to evaluate the whole triangle ! (Or just hard-code it.)
If you need a single element, this recurrence is attractive. Use symmetry for k above n/2 (C(n,k) = C(n,n-k)).

Your implementation cannot handle even moderately large values of n because factorial(n) causes an arithmetic overflow for n >= 13.
Here is a simplistic recursive implementation that can handle larger values, albeit very slowly:
#include <stdio.h>
int combination(int n, int k) {
if (n < 0 || k < 0 || k > n)
return 0;
if (k == 0 || k == n)
return 1;
return combination(n - 1, k - 1) + combination(n - 1, k);
}
int main() {
int lines, i, j;
printf("Number of Pascal Triangle lines: ");
if (scanf("%d", &lines) != 1)
return 1;
for (i = 0; i <= lines; i++) {
for (j = 0; j <= i; j++) {
printf("%d ", combination(i, j));
}
printf("\n");
}
return 0;
}
Notes:
This implementation illustrates how vastly inefficient recursive implementations can become.
Since you are printing a complete triangle, you should store intermediary results and compute one full line at a time from the previous line very efficiently, but still limited by the range of unsigned long long, 67 lines.
Here is a faster alternative:
#include <stdio.h>
int main() {
int lines, i, j;
printf("Number of Pascal Triangle lines: ");
if (scanf("%d", &lines) != 1 || lines < 0 || lines > 67)
return 1;
unsigned long long comb[lines + 1];
for (i = 0; i <= lines; i++) {
comb[i] = 0;
}
comb[0] = 1;
for (i = 0; i <= lines; i++) {
for (j = i; j > 0; j--) {
comb[j] += comb[j - 1];
}
for (j = 0; j <= i; j++) {
printf("%llu ", comb[j]);
}
printf("\n");
}
return 0;
}

Hope the following code might help ::
/*elements of the pascal's trianlge for 10 rows*/
#include<stdio.h>
int main()
{
int p[11][11];
int i,j,k;
for(i=1;i<=10;i++)
{
/*creating whitespaces*/
for(k=i;k<=10;k++)
{
printf(" ");
}
for(j=1;j<=i;j++)
{
/*printing the boundary elements i.e. 1*/
if(j==1 || i==j)
{
p[i][j]=1;
printf("%3d ",p[i][j]);
}
/*printing the rest elements*/
else
{
p[i][j]=p[i-1][j-1]+p[i-1][j];
printf("%3d ",p[i][j]);
}
}
printf("\n");
}
}
Thanks

Related

How to make competitive coding solutions more efficient (BIT wise operations)?

How do I make my code more efficient (in time) pertaining to a competitive coding question (source: codechef starters 73 div 4):
(Problem) Chef has an array A of length N. Chef wants to append a non-negative integer X to the array A such that the bitwise OR of the entire array becomes = Y .
Determine the minimum possible value of X. If no possible value of X exists, output -1.
Input Format
The first line contains a single integer T — the number of test cases. Then the test cases follow.
The first line of each test case contains two integers N and Y — the size of the array A and final bitwise OR of the array A.
The second line of each test case contains N space-separated integers A_1, A_2, ..., A_N denoting the array A.
Please don't judge me for my choice of language .
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int* binary_number(int n) // returns pointer to a array of length 20(based on given constrains) representing binary
{
int* ptc;
ptc = (int*) malloc(20*sizeof(int));
for(int i = 0; i < 20; i++)
{
if((n / (int) pow(2,19-i)) > 0){*(ptc + i) = 1;}
else {*(ptc + i) = 0;}
n = n % (int) pow(2,19-i) ;
}
return ptc;
}
int or_value(int* ptc, int n) // Takes in pointers containing 1 or zero and gives the logical OR
{
for(int k = 0; k < n; n++)
{
if(*ptc == *(ptc + 20*k)){continue;} // pointers are 20 units apart
else{return 1;break;}
}
return *ptc;
}
int main(void) {
int t; scanf("%d", &t);
for (int i = 0; i < t; i++)
{
int n, y;
scanf("%d %d", &n, &y);
int a[n];
for(int j = 0; j < n ; j++)
{
scanf("%d", &a[j]);
}
int b[20*n];
for (int j = 0; j < n; j++)
{
for (int k = 0; k < 20; k++)
{
b[20*j + k] = *(binary_number(a[n])+k);
}
}
int c = 0;
int p = 0;
for (int j = 0; j < 20; j++)
{
if ((*(binary_number(y) + j) == 1) && (or_value((&b[0] + j),n) == 0)){c = c + pow(2,19 - j);}
else if ((*(binary_number(y) + j) == 0) && (or_value((&b[0] + j),n) == 1)){p = 1; break;}
}
if (p==1){printf("-1");}
else {printf("%d\n", c);}
}
return 0;
}

How can I make a function and get cumulative sum of previous numbers?

What I want to do is to get a cumulative sum of previous integers starting from 1, for example:
If my input is 4, then the function should work in this way;
1 + (1+2) + (1+2+3) + (1+2+3+4) = 20.
And the output needs to be 20. Also, I have to get this done by a function, not in main(); function while using int n as the only variable.
What I've tried is to make a function which adds from 1 to integer N, and use 'for'to make N start from 1, so that it can fully add the whole numbers until it reaches N.
#include <stdio.h>
int sum(int n);
int main() {
int n, input, sum;
sum = 0;
scanf("%d", &n);
for (n = 0; n <= input; n++) {
sum += n;
}
printf("%d", sum);
return 0;
}
int sum(int n) {
int i, n, sum = 0;
scanf("%d", &n);
for (i = 1; i <= n; i += 1){
sum += i;
}
return n;
}
What I expected when the input is 4 is 20, but the actual output is 10.
I would have written it this way, remarks are where changes been made
#include <stdio.h>
int sum(int n);
int main() {
int n, input, sum;
// sum = 0; // no need for this
scanf("%d", &n);
/* the next for has no use
for (n = 0; n <= input; n++) {
sum += n;
} */
// I would be adding some input sanitazing if possible here
printf("%d", sum(n));
return 0;
}
int sum(int n) {
int i, /*n, */ rsum = 0; // n is already a parameter, rsum for running sum
// scanf("%d", &n); // nope nope, scanf and printf should be avoided in functions
for (i = 1; i <= n; i++){ // changed i +=1 with i++ , easier to read
for (j=1;j<=i;j++) // need this other loop inside
rsum += j;
}
return rsum;
}
Here it is with a single loop; very fast.
#include <stdio.h>
int cumulative_sum(int m)
{
int sum = 0;
for(int n=1; n<=m; ++n) sum += n*(n+1);
return sum/2;
}
int main(void)
{
int n;
printf("Input value N: ");
scanf("%d", &n);
printf("Answer is %d\n", cumulative_sum(n));
return 0;
}
The main issue is in the function, you are doing only 1 loop (you have also some logical things, which compiler should tell you, like same naming of variable and function.. eg.),
so in case you will put 4 as the input, loop will do only 1+2+3+4, but your case if different, you want to make suma of all iterations like 1 + (1+2) + (1+2+3) + (1+2+3+4)
you are doing only last step basically (1+2+3+4), 4 iterations (4x suma), but actually you need 10 iterations (due suma of all particular suma of elements)
As suggested, try to debug your code - What is a debugger and how can it help me diagnose problems?
- it will really help you do understand your code
As mentioned, the issue is in
int sum(int n) {
int i, n, sum = 0;
scanf("%d", &n);
for (i = 1; i <= n; i += 1){
sum += i;
}
return n;
}
You have to make two loops eg. like follows:
int sum,n = 0;
//scanf("%d", &n);
n = 4; //input simulation
//just for demonstration
int iterations = 0;
//counter for total loops (how many "brackets" needs to be count)
for(int loopsCounter = 1; loopsCounter <= n;loopsCounter++){
//counter for child elements in brackets (like 1+2 ,1+2+3, ..)
for (int sumaLoopCounter = 1; sumaLoopCounter <= loopsCounter; sumaLoopCounter++){
//simply make sum with the given number
/* first step 0 +1
second 1+2 added to previous suma = 1+3
third 1+2+3,.. added to previous = 4+6
...
*/
sum += sumaLoopCounter;
//just testing for demonstration
iterations++; //iterations = iterations + 1
}
}
printf("%i \n",iterations);
printf("%i",sum);
Then you got output as expected - sum of all "bracket elements" and 10 iterations, which matches numbers of needed additions
10
20

c programming - printing sequence of sum of squared digits (as an array) for a potential happy number

I have this assignment for my intro to C programming class and part of my code has to find the sequence of the sum of square digits of a number in order to determine after if the given number is a happy number (sum of square digits = 1)
Here's part of my code:
#include <stdio.h>
#include <math.h>
// The sum of square digits function
int sqd (int x) {
int sum = 0;
while (x > 0) {
sum = sum + pow(x%10, 2);
x = x/10;
}
return sum;
}
// The search function
int search (int a[], int val, int size) {
int i;
for (i = 0; i < size; i++) {
if (a[i] == val) {
return 1;
}
}
return 0;
}
// The main program
void main () {
int a [1000] = {0};
int N;
int count = 1;
int j;
printf("Please enter the potential happy number:\n", N);
scanf ("%d", &N);
a[0] = N;
a[count] = sqd (N);
do {
a[count] = sqd (a[count-1]);
count++;
} while (search (a, a[count], count));
for ( j = 0; j <= count; j++) {
printf("%d\n", a[j]);
}
}
It only prints the first three sums in the sequence. I really don't know how to make it work.
Thank you in advance
This line
while (search (a, a[count], count));
makes sure that you break out of the loop after one round since a[1] is not equal toa[0]. You can change that line to be:
while (a[count-1] != 1);
You also need to add a clause to make sure that you stop when the limit of the array is reached. Update that line to be:
while (a[count-1] != 1 && count < 1000 );
And then, change the printing loop to use i < count, not i <= count. Using <= will result in accessing the array out of bounds when the user enters a sad number.
for ( j = 0; j < count; j++){
printf("%d\n", a[j]);
}
Update
After a bit of reading on happy numbers at Wikipedia, I understand why you had call to search in the conditional of the while. The following also works.
} while ( ! (a[count-1] == 1 || search(a, a[count-1], count-1)) );
That will search for the last number in the array but only up to the previous index.

Prime numbers in C and is_prime

I'm writing a program to find all of the prime numbers contained within a user input n. I am having trouble with the is_prime function.
#include <stdio.h>
#include <math.h>
main() {
int n;
int k;
// gets user input for length of string
// and stores it as n
printf("Enter the value of n:");
scanf("%d", &n);
for (k = 2; k <= n; k++) {
if (is_Prime(k) == 1) {
printf("Printing primes less than or equal to %d: /n %d, &n, &k");
}
}
I want the output to look like this, but I am not sure how to print the list without using different variables for each prime number.
Printing primes less than or equal to 30:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29.
//here is the is_Prime function
is_Prime (int n)
{
for(j = 2; j <= n/2; j++)
{
if(n%j != 0)
{
return 1;
break;
}
}
if(n%j == 0 )
return 0;
}
I am not sure how to call the is_prime subroutine? Any help?
printf("Printing primes less than or equal to %d:\n", n);
for(k = 2; k <= n; k++)
{
if(is_Prime(k) == 1)
{
printf("%d, ", k);
}
}
printf("Printing primes less than or equal to %d:\n%s", n, (n >= 2 ? "2" : ""));
for (k = 3; k <= n; ++k)
if (is_Prime(k))
printf(", %d", k);
printf("%s\n", (n >= 2 ? "." : ""));
Here's a slightly cleaner version of your is_Prime function:
int is_Prime(int n)
{
if (n < 2)
return 0;
int last = (int) sqrt(n) + 1; /* conservatively safe */
for (int j = 2; j <= last; ++j)
if (0 == n % j)
return 0;
return 1;
}
Note that you only really need to check up to the sqrt() of a number to find all its potential factors.
Also note that this is not a great way to find all the primes less than n, which is the prime purpose of your program, especially when you will repeatedly call this function incrementing n by 1 each time. I recommend trying to implement the Sieve of Eratosthenes or the Sieve of Sundaram instead -- so long as n isn't too large.

intersection and union of n-arrays in C

I have those functions which are making intersection/union but just of two arrays.
I need too improve them to work with n-arrays: arr = {{1,2,3},{1,5,6},...,{1,9}}.
The arrays are sorted , and their elements are unique among them.
Example (intersection):
Input: {{1,2,3,4},{2,5,4},{4,7,8}}
Output: {4}
arr1[],arr2 - arrays
m,n - length of the arrays
Intersection function:
int printIntersection(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while(i < m && j < n)
{
if(arr1[i] < arr2[j])
i++;
else if(arr2[j] < arr1[i])
j++;
else /* if arr1[i] == arr2[j] */
{
printf(" %d ", arr2[j++]);
i++;
}
}
}
and union function:
int printUnion(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while(i < m && j < n)
{
if(arr1[i] < arr2[j])
printf(" %d ", arr1[i++]);
else if(arr2[j] < arr1[i])
printf(" %d ", arr2[j++]);
else
{
printf(" %d ", arr2[j++]);
i++;
}
}
while(i < m)
printf(" %d ", arr1[i++]);
while(j < n)
printf(" %d ", arr2[j++]);
}
union(a, b, c) = union(union(a, b), c), and the same goes for intersection(). I.e. you can decompose the union or intersection of n sets into n unions or intersections of 2 sets (as NuclearGhost points out in a comment on the question). What you need to do is change your current functions so that they build up a resulting set, instead of immediately printing the result. You can then make a separate function that prints a set.
For efficiency, you want to take the union or intersection of sets that are roughly of equal size. So a divide-and-conquer approach should work alright, assuming that all input sets are likely to be of roughly equal size.
void intersection(int arr1[], int arr2[], int m, int n, int *out)
{
int i = 0, j = 0;
while(i < m && j < n)
{
if(arr1[i] < arr2[j])
i++;
else if(arr2[j] < arr1[i])
j++;
else /* if arr1[i] == arr2[j] */
{
*out++ = arr2[j++];
i++;
}
}
}
void multi_intersection(int n, int **arrays, int *lengths, int *out) {
if (n == 2) {
intersection(arrays[0], arrays[1], lengths[0], lengths[1], out);
} else if (n == 1) {
memcpy(out, arrays[0], lengths[0] * sizeof (int));
} else {
/* Allocate buffers large enough */
int *buf[2];
int len[2] = { INT_MAX, INT_MAX };
int i;
for (i = 0; i < n; ++i) {
int which = i < n / 2;
if (lengths[i] < len[which]) len[which] = lengths[i];
}
buf[0] = malloc(len[0] * sizeof (int));
buf[1] = malloc(len[1] * sizeof (int));
/* Recurse to process child subproblems */
multi_intersection(n / 2, arrays, lengths, buf[0]);
multi_intersection(n - n / 2, arrays + n / 2, lengths + n / 2, buf[1]);
/* Combine child solutions */
intersection(buf[0], buf[1], len, out);
free(buf[0]);
free(buf[1]);
}
Similar code works for multi_union(), except that the buffer lengths need to be calculated differently: the result of a union could be as large as the sum of the sizes of the inputs, rather than the minimum size of the inputs. It could probably be rewritten to do less buffer allocation. Also the recursion could be rewritten to use iteration, the same way mergesort can be written to use iteration, but the current recursive approach uses only O(log n) additional stack space anyway.
presume the max value in arrays is less than K. N is the number of arrays
int Result[K] = {0};
intersection function
//input array1
int index = 0;
for(; index < arrary1len;index++)
{
Result[array1]++;
}
.....
for(index = 0; index < K; index++)
{
if(Result[index] == N)
printf("%d",index);
}

Resources