write program to perform sum = 1+ (1+2) + (1+2+3) + ... + (1+2...+n)
I can't get the codes right. Can somebody help?
#include<stdio.h>
int main()
{
int n, sum,i,j;
printf("Please enter an integer, n = ");
scanf("%d", &n);
for(i=1;i<=n;开发者_JAVA技巧i++)
for(j=1;j<=i;j++)
sum = sum + n;
printf("sum = %d", sum);
return 0;
}
- You are not initialising
sum. Initialise it with0. - You shouldn't be adding
nat each step, butj.
Of course, this is to fix your current code. There are better approaches to solving the problem, which others have already mentioned.
Edit:
Just for fun, here's a formula that allows you to solve the problem in O(1):
Your sum is equal to n*(n + 1)*(2*n + 1) / 12 + n*(n + 1) / 4.
This is obtained by writing it as a sum and using the fact that the sum of the first n consecutive squares is n(n + 1)(2n + 1) / 6 and the sum of the first n positive ints is n(n + 1)/2. +1 if you can find a nicer form of the formula.
No need for recursion, just look at the math:
1 + (1+2) + (1+2+3) + ... + (1+2+3+...+n)
is equal to
1*n + 2*(n-1) + 3*(n-2) + ... + n
Not what you expected, but this is the best solution ;)
int calculate (int n) {
return (2*n + 3*n*n + n*n*n) / 6;
}
Think this through. You have one sum you're accumulating, and you have a series of values. Each value can be generated from the previous one by adding the index. So why do you have nested loops?
Doing it iteratively, like you tried:
#include <stdio.h>
int main() {
int i, t, n, sum;
printf("Please enter an integer, n = ");
scanf("%d", &n);
t = sum = 0;
for (i = 1; i <= n; ++i) {
t += i;
sum += t;
}
printf("sum = %d\n", sum);
return 0;
}
But there's a closed-form formula as IVlad suggested.
You never initialize sum, so you're adding everything to a random garbage value. Stick sum = 0; before your loops
Start with the math, see if you can find some pattern.
if n = 0 , res = 0?
if n = 1 , res = 1
if n = 2 , res = 1 + (1+2)
if n = 3 , res = 1 + (1+2) + (1+2+3)
for each n, res is ??
Try:
int main(void)
{
int n, sum;
printf("\nPlease enter a postive integer value");
scanf("%d", &n);
sum = n * ( n + 1 )/ 2;
printf("\n%d", sum);
return 0;
}
Try this:
int main(void)
{
int total=1;
int sumtotal = 0;
int n=5;
for(int i=1; i<=n; i++)
{
total+=i;
sumtotal+=total;
}
//sumtotal should give you 1+(1+2)+(1+2+3)
return 0;
}
n * (n -(n - 1))
int n, sum
for n = 0; n <= 3; n ++ {
sum += n * (n -(n - 1))
}
works for factorials too (change operator and set sum to 1):
int n, sum
sum = 1
for n = 0; n <= 3: n++{
sum *= n * (n -(n -1))
}
加载中,请稍侯......
精彩评论