Calculate sum of M natural numbers starting from N.
-
Calculate sum of M natural numbers starting from N, where N and M should be read from standard input (separated by space). User FOR statement.
Example
Input:
3 4
Output:
18So my code is:
#include int main(){
int i,n,m,sum;
scanf("%d %d",&n,&m);
sum=n;
for(i=0;i<=m;i++)
sum=sum+i;
printf("%d",sum);
}
I set i=0 because I figured since the sum is supposed to start from N itself then that's the way to do it. The problem is though it doesn't work the way it should. What's wrong with my code? :sigh: -
Calculate sum of M natural numbers starting from N, where N and M should be read from standard input (separated by space). User FOR statement.
Example
Input:
3 4
Output:
18So my code is:
#include int main(){
int i,n,m,sum;
scanf("%d %d",&n,&m);
sum=n;
for(i=0;i<=m;i++)
sum=sum+i;
printf("%d",sum);
}
I set i=0 because I figured since the sum is supposed to start from N itself then that's the way to do it. The problem is though it doesn't work the way it should. What's wrong with my code? :sigh:Member 13478986 wrote:
sum=n; for(i=0;i<=m;i++) sum=sum+i;
1. you are trying to sum (M+1) natural numbers: starting with 0 and ending with M... 2. You are trying to sum not was required (i.e. N + N+1 + N+2 ... + N+M) but (N + 0 + 1 + ... + M)
-
Member 13478986 wrote:
sum=n; for(i=0;i<=m;i++) sum=sum+i;
1. you are trying to sum (M+1) natural numbers: starting with 0 and ending with M... 2. You are trying to sum not was required (i.e. N + N+1 + N+2 ... + N+M) but (N + 0 + 1 + ... + M)
that helped a lot, i changed it to
sum=0;
for(i=0;i
works as it should, thanks! -
Calculate sum of M natural numbers starting from N, where N and M should be read from standard input (separated by space). User FOR statement.
Example
Input:
3 4
Output:
18So my code is:
#include int main(){
int i,n,m,sum;
scanf("%d %d",&n,&m);
sum=n;
for(i=0;i<=m;i++)
sum=sum+i;
printf("%d",sum);
}
I set i=0 because I figured since the sum is supposed to start from N itself then that's the way to do it. The problem is though it doesn't work the way it should. What's wrong with my code? :sigh:You need no iteration, actually. Since (see 1 + 2 + 3 + 4 + ⋯ - Wikipedia[^])
1 + 2 + ... + n = n * (n + 1) / 2
In your case
SUM = ((N + M - 1) * (N + M) - (N - 1) * (N)) / 2
Let's try the formula with the input
N=3, M=4
SUM = ((3 + 4 -1) * (3 + 4) - (3) * (2)) / 2 = (6 * 7 - 3 * 2) / 2 = (42 - 6) / 2 = 18
-
You need no iteration, actually. Since (see 1 + 2 + 3 + 4 + ⋯ - Wikipedia[^])
1 + 2 + ... + n = n * (n + 1) / 2
In your case
SUM = ((N + M - 1) * (N + M) - (N - 1) * (N)) / 2
Let's try the formula with the input
N=3, M=4
SUM = ((3 + 4 -1) * (3 + 4) - (3) * (2)) / 2 = (6 * 7 - 3 * 2) / 2 = (42 - 6) / 2 = 18
yeah I mean it's just an arithmetic sequence so the easiest way would be to just use the formula. the thing is the task requires using the "for" loop so I had to.