My teacher wants the sum of all numbers from x to y... like x+(x+1)+(x+2)...until y. But I think I'm doing something wrong here!
Can someone advice me what is wrong here?
#include <stdio.h>
int sum_naturals(int n)
{
return (n-1) * n / 2;
}
int sum_from_to(int m)
{
return (m-1) * m / 2;
}
void test_sum_naturals(void)
{
int x;
scanf("%d", &x);
int z = sum_naturals(x);
printf("%d\n", z);
}
void test_sum_from_to(void)
{
int x;
int y;
scanf("%d", &x);
scanf("%d", &y);
int z = sum_naturals(x);
int b = sum_from_to(y);
printf("%d\n", z);
}
int main(void)
{
//test_sum_naturals();
test_sum_from_to();
return 0;
}
Your code should in fact be:
int sum_naturals(int n)
{
return (n+1) * n / 2;
}
int sum_from_to(int m)
{
return (m+1) * m / 2;
}
Notice + instead of your -.
To find the sum just add in the function test_sum_from_to this line:
printf("The sum is %d", b-z);
Here's one solution :
#include<stdio.h>
int sum_naturals(int n)
{
return (n+1) * n / 2;
}
int sum_from_x_to_y(int x, int y){
return sum_naturals(y) - sum_naturals(x);
}
main()
{
printf ("Sum: %d \n",sum_from_x_to_y(5, 10));
printf ("Sum: %d \n",sum_from_x_to_y(0, 10));
printf ("Sum: %d \n",sum_from_x_to_y(0, 5));
return 0;
}
Note : sum from 0 to N is (n+1)*n/2 and not (n-1)*n/2
Related
Calculating the sum of the first k numbers of the sequence a[0] = 1, a[k] = k*a[k-1] +1/k ( k = 1, 2, ... ).
UPD
There is still a problem with the recursive function ...What is the error?
#include <stdio.h>
#include <stdlib.h>
float m(float n){
float k=1;
float sum=k;
int i;
for (i=1; i<n;i++){
k = (i*k+1.0/i);
sum = sum+k;
}
return sum;
}
float Fn(float n)
{
if (n==0) {
return 1;}
return ((n*Fn(n-1)+1.0/n)+Fn(n-1));
}
int main(int argc, char *argv[]) {
float k;
printf("input k : ");
scanf("%f",&k);
printf("res %f \n",Fn(k));
return 0;
}
There were several issues in your code:
Integer division: 1/n = 0
There was a confusion between the term value Fn and the sum value
An iterative solution is simpler here than a recursive one
Here is a code, with both iterative and recursive implementations:
#include <stdio.h>
#include <stdlib.h>
float sum_fn(int n){
float Fk = 1;
float sum = Fk;
for (int i = 1; i <= n; i++){
Fk = i*Fk + 1.0/i;
sum += Fk;
}
return sum;
}
float sum_recursive(int n, float *sum){
if (n == 0) {
*sum += 1.0;
return 1.0;
}
float Fn = n * sum_recursive(n-1, sum) + 1.0/n;
*sum += Fn;
return Fn;
}
int main(int argc, char *argv[]) {
int k;
printf("input k : ");
scanf("%d", &k);
printf("k = %d\tsum = %f\n", k, sum_fn(k));
float sum = 0;
sum_recursive(k, &sum);
printf("k = %d\tsum = %f\n", k, sum);
return 0;
}
How would you convert the following recursive program with dynamic programming (DP)?
I'm just having a little trouble trying to redefine this code into a dynamic programming form. I got the base case and the general case identified, and I am aware that DP is about a "bottom-up" approach.
int add(int, int);
int main()
{
int x = 0, y = 0;
printf("Enter positive integers x, y: ");
scanf("%d %d", &x, &y);
printf("Result: %d\n", add(x, y));
return 0;
}
int add(int x, int y)
{
if(x < 0 || y < 0){
fprintf(stderr, "Negative Integer received!\n");
return -1;
}
if (x == 1 || y == 1)
return 1;
else
return add(x, y-1) + add(x - 1, y) + add(x-1, y-1);
}
Why do you want to do it in recursive way? There is an iterative way, and iterative 'almost always' beats recursive. Besides it is less code:
int DP[500][500];
memset(DP, 0, sizeof(DP));
for(int i=1; i<=x; i++) DP[i][1] = 1;
for(int i=1; i<=y; i++) DP[1][i] = 1;
for(int i=2; i<=x; i++) {
for(int j=2; j<=y; j++) {
DP[i][j] = DP[i-1][j-1] + DP[i-1][j] + DP[i][j-1];
}
}
printf("Result: %d\n", DP[x][y]);
But if you insist on recursion you can pass your DP array to function by pointer. And every time check if you calculated DP[i][j] before, if so don't calculate it again and return back:
#include <stdio.h>
#include <string.h>
void add(int x, int y, int (*M)[500])
{
if(M[x][y] > 0) return;
if (x == 1 || y == 1) {
M[x][y] = 1;
return;
}
add(x, y-1, M);
add(x - 1, y, M);
add(x-1, y-1, M);
M[x][y] = M[x][y-1] + M[x-1][y] + M[x-1][y-1];
return;
}
int main()
{
int x, y;
printf("Enter x, y: ");
scanf("%d %d", &x, &y);
int DP[500][500];
memset(DP, 0, sizeof(DP));
add(x, y, DP);
printf("Result: %d\n", DP[x][y]);
return 0;
}
Your code will cause stack overflow for all the possible x,y and z integer(negative, positive) combinations
I am given 5 integers that must be not less than 10 and not more than 100. Then, I must find their division remainders if we divide them by 10. Then, I must find the sum of the remainders that I found and (there it goes the difficult part) finally which one of the 5 remainders is the max.
Here, I give you the code that I wrote but I have no idea how to go further. Maybe with "for", but I don't imagine how exactly.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a, b, c, d, e, a10,b10,c10,d10,e10, sum, max;
printf("give 5 integers \n");
scanf("%d %d %d %d %d", &a, &b, &c, &d, &e);
a10 = a % 10;
b10 = b % 10;
c10 = c % 10;
d10 = d % 10;
e10 = e % 10;
printf("division remainder is: %d %d %d %d %d\n",
a10,b10,c10,d10,e10);
sum = a10 + b10 + c10 + d10 + e10;
printf("the sum of the remains is: %d\n", sum);
system("pause");
}
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h>
int *rands_range(int n, int low, int high);
void print(FILE *fp, int n, int *nums);
int *map(int n, int *nums, int (*f)(int));
int fold(int n, int *nums, int init, int (*f)(int, int));
int add(int x, int y);
int rem10(int x);
int greater(int x, int y);
int main(void){
srand(time(NULL));
int n = 5;
printf("give 5 integers\n");
int *integers = rands_range(n, 10, 100);
print(stdout, n, integers);
putchar('\n');
printf("division remainder is: ");
int *rems = map(n, integers, rem10);
print(stdout, n, rems);
putchar('\n');
int sum = fold(n, rems, 0, add);
printf("the sum of the remains is: %d\n", sum);
putchar('\n');
int max = fold(n, rems, *rems, greater);
printf("the max of the remains is: %d\n", max);
putchar('\n');
free(integers);
free(rems);
system("pause");
}
int *rands_range(int n, int low, int high){
assert(n > 0 && RAND_MAX >= high - low && high >= low);
int *values = malloc(n * sizeof(*values));
if(values){
for(int i = 0; i < n; ++i){
values[i] = low + rand() % (high-low+1);
}
}
return values;
}
void print(FILE *fp, int n, int *nums){
for(int i = 0; i < n; ++i){
if(i)
fprintf(fp, ", ");
fprintf(fp, "%d", nums[i]);
}
fprintf(fp, "\n");
}
int remainder_int(int x, int y){
return x % y;
}
int add(int x, int y){
return x + y;
}
int rem10(int x){
return remainder_int(x, 10);
}
int greater(int x, int y){
return x > y ? x : y;
}
int *map(int n, int *nums, int (*f)(int)){
int *result = malloc(n * sizeof(*result));
if(result){
for(int i = 0; i < n; ++i){
result[i] = f(nums[i]);
}
}
return result;
}
int fold(int n, int *nums, int init, int (*f)(int, int)){
int acc = init;
for(int i = 0; i < n; ++i){
acc = f(acc, nums[i]);
}
return acc;
}
Functions with variable arguments:
#include <stdio.h>
#include <stdarg.h>
#include <limits.h>
int max(int n, ...){
int ret = INT_MIN;
va_list ap;
va_start(ap, n);
while(n--){
int wk = va_arg(ap, int);
if(ret < wk)
ret = wk;
}
va_end(ap);
return ret;
}
int sum(int n, ...){
int sum = 0;
va_list ap;
va_start(ap, n);
while(n--){
sum += va_arg(ap, int);
}
va_end(ap);
return sum;
}
int main(void){
int a = 6, b = 3, c = 9, d = 2, e = 8;
printf("sum:%d\n", sum(5, a, b, c, d, e));
printf("max:%d\n", max(5, a, b, c, d, e));
}
Following is the code using 'for' and int array. To use 'for' you must need to use array.
#include<stdio.h>
#include <stdlib.h>
int main()
{
int i;
int max;
int sum=0;
int aryNum[5];
int aryRem[5];
printf("give 5 integers \n");
for(i=0;i<5;i++)
{
scanf("%d",&aryNum[i]);
}
printf("division remainder is: ");
for(i=0;i<5;i++)
{
aryRem[i]=aryNum[i]%10;
printf("%d ",aryRem[i]);
}
printf("\n");
max=aryRem[0];
sum = max;
for(i=1;i<5;i++)
{
if(max<aryRem[i])
{
max=aryRem[i];
}
sum+=aryRem[i];
}
printf("the sum of the remains is: %d\n", sum);
printf("maximum remains is: %d\n", max);
system("pause");
return 0;
}
If you don't want to use 'for' and int array then you can use following code. But it is not advisable:
#include <stdio.h>
#include <stdlib.h>
int greater(int a, int b)
{
return (a>b)? a:b;
}
int main()
{
int a, b, c, d, e, a10,b10,c10,d10,e10, sum, max;
printf("give 5 integers \n");
scanf("%d %d %d %d %d", &a, &b, &c, &d, &e);
a10 = a % 10;
b10 = b % 10;
c10 = c % 10;
d10 = d % 10;
e10 = e % 10;
printf("division remainder is: %d %d %d %d %d\n",
a10,b10,c10,d10,e10);
sum = a10 + b10 + c10 + d10 + e10;
printf("the sum of the remains is: %d\n", sum);
/*New added code*/
max=greater(a10,b10);
max=greater(max,c10);
max=greater(max,d10);
max=greater(max,e10);
printf("maximum remains is: %d\n", max);
system("pause");
return 0;
}
I wish to write a program which calculates the series x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!) by taking x and n as user inputs.
This is what i've tried, and well there's no output when I enter the values for x,n:
#include<stdio.h>
#include<math.h>
//#include<process.h>
#include<stdlib.h>
double series(int,int);
double factorial(int);
int main()
{
double x,n,res;
printf("This program will evaluate the following series:\nx-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf("\nPlease enter a value for x and an odd value for n\n");
scanf("%lf%lf",&x,&n);
/*if(n%2!=0)
{
printf("Please enter a positive value!\n");
exit(0);
}*/
res=series(x,n);
printf("For the values you've entered, the value of the series is:\n %lf",res);
}
double series(int s, int t)
{
int i,sign=1; double r,fact,exec;
for(i=1;i<=t;i+2)
{
exec=sign*(pow(s,i)/factorial(i));
r+=exec;
sign*=-1;
}
return r;
}
double factorial(int p)
{
double f=1.0;
while(p>0)
{
f*=p;
p--;
}
return f;
}
When I enter values for x and n, it simply shows nothing.
While I've written in C, C++ solutions are also appreciated.
Output window in code::blocks
The loop
for(i=1;i<=t;i+2)
in the function series() is an infinite loop when t >= 1 because i isn't updated in the loop. Try changing + to += and use
for(i=1;i<=t;i+=2)
instead. Also it seems you should use type int for x and n in the function main() because the arguments of series() is int. Don't forget to change the format specifier when changing their types.
Thanks to all those who helped. Here's the final working code:
#include<stdio.h>
#include<math.h>
#include<process.h>
#include<stdlib.h>
double series(int,int);
double factorial(int);
int main()
{
int x,n; double res;
printf("This program will evaluate the following series:\nx-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf("\nPlease enter a value for x and an odd value for n\n");
scanf("%d%d",&x,&n);
if(n%2==0)
{
n=n-1;
}
res=series(x,n);
printf("For the values you've entered, the value of the series is:\n%lf",res);
}
double series(int s, int t)
{
int i,sign=1; double r=0.0,fact,exec;
for(i=1;i<=t;i+=2)
{
exec=sign*(pow(s,i)/factorial(i));
r+=exec;
sign*=-1;
}
return r;
}
double factorial(int p)
{
double f=1;
while(p>0)
{
f*=p;
p--;
}
return f;
}
in loop we step by two for getting odd numbers.by multiplying the current temp variable by the previous temp variable in the loop with neccesary terms like x square and dividing by i*(i-1) i.e for factorial and multiply with -1 i.e to achive negavtive number alternatively. by using this temp variable and adding it to sum variable in every iteration will give us answer.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n, x;
cout << "enter x and no.of terms: ";
cin >> x >> n;
float sum = 0, temp = x;
for (int i = 3; i < 2 * n + 2; i = i + 2)
{
temp = ((-1 * temp) *(x*x)) / i*(i-1);
sum = sum + temp;
}
cout << x + sum;
return 0;
}
// series x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)
#include<stdio.h>
#include<math.h>
double factorial (int);
double calc (float, float);
int
main ()
{
int x, deg;
double fin;
printf ("x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf ("Enter value of x\n");
scanf ("%d", &x);
printf ("highest degree in denom i.e., 1 or 3 or 5 whatever, it should be odd .\n");
scanf ("%d", °);
fin = calc (x, deg);
printf ("the summation of series =%1f\n", fin);
return 0;
}
double calc (float num, float res)
{
int count, sign = 1;
double rres = 0;
for (count = 1; count <= res; count += 2)
{
rres += sign * (pow (num, count) / factorial (count));
sign *= -1;
}
return (rres);
}
double factorial (int num)
{
int count;
double sum = 1;
for (count = 1; count <= num; count++)
{
sum *= count;
}
return (sum);
}
I'm trying to find nCr value. There is no error but I'm getting 1 as the answer for all the inputs. Help me find the solution please.
#include <stdio.h>
int fact(int num)
{
int f=1,i;
for(i=1;i<=num;i++)
{
f=f*1;
}
return f;
}
int main(void)
{
int n,r,ncr=0;
printf("\n enter n and r values");
scanf("%d%d",&n,&r);
ncr=(fact(n) / (fact(r) * fact(n-r)));
printf("\n ncr for %d and %d is %d",n,r,ncr);
return 0;
}
It should not be f = f *1, but rather f = f * i
Your factorial code is incorrect.
You set f = 1, then do f = f * 1 a bunch of times. Then return f which is still 1. I think you mean f = f*i right?
int fact(int num)
{
int f=1,i;
for(i=1;i<=num;i++)
{
f=f*i;
}
return f;
}
Your method to compute factorial needs a correction. Should be :
int fact(int num)
{
int f=1,i;
for(i=1;i<=num;i++)
{
f=f*i;
}
return f;
}
Also, nCr is not defined if r > n. You should add this check after your scanf call.
Something like :
if (r > n) printf("r cannot be greater than n.").
A more standard form of computing factorial is one that uses recursion.
int fact(int num)
{
if (num == 1 || num == 0)
return 1;
else
return (num * fact(num - 1));
}
A better and faster approach would be to calculate nCr like this
int nCr(int n, int r) {
if (r > n / 2) r = n - r;
int ans = 1, i;
for (i = 1; i <= r; i++) {
ans *= n - r + i;
ans /= i;
}
return ans;
}