Home > Back-end >  An algorithm about the C language, ask for advice
An algorithm about the C language, ask for advice

Time:06-04

I was a small white C language, want to ask the great spirit how to implement the sum using a for statement=2 + 4 + 6 + 8 +... + 100 thank you!

CodePudding user response:

 
int i;
Int sum=0;
For (I=2; I & lt;=100; I +=2)
{
The sum +=I;
}
Printf (" sum=% d \ n ", sum);

CodePudding user response:

Int sum=0;
For (int I=2; i<=100; I + +==2) sum I;

CodePudding user response:

Int=0, iI iSum=0;
For (=2 iI; II<=100; II +=2)
{
ISum +=iI;
}

CodePudding user response:

This requirement, there are a few knowledge about:
1, how to record 2 + 4 + 6 +... + 100 values.
Sum=0;//the initial value of 0.
Sum=sum + 2;//at this point, the sum=0 + 2
Sum=sum + 4;//at this point, the sum=0 + 2 + 4;

So the sum=sum + n is recorded all the addend and simple algorithm.

2, how to cycle?
2,4,6,8,10,
Obviously, the difference between two Numbers is 2.
That is:
Sum=0;
I=0 - & gt; Sum=sum + I - & gt; 0 + 0 - & gt; 0
I=2 - & gt; Sum=sum + I - & gt; 0 + 2 - & gt; 2
I=4 - & gt; Sum=sum + I - & gt; 2 + 4 - & gt; 6
.
So circulation initial values starting from 0, at the end of 100, each loop step 2:
for(i=0; i<=100; I +=2) {
sum=sum+i;//- & gt; sum+=i;
}

CodePudding user response:

This is an arithmetic progression: 2,4,6,8,10... 100,
Summation formula: a1 + n * n (n - 1)/2 d

2 + 4 + 6 + 8... Tolerance of 2 + 100 is o the top 50 and arithmetic progression,
Using C language implementation is
Int a1=2;
Int n=50;
Int d=2;
Int a1 + sum=n * n * (n - 1) * d/2;
Printf (" sum=% d \ n ", sum);

When the input number is very big, this is faster than a for loop will be many,

This will be faster than the for loop,

CodePudding user response:

reference 5 floor qq_35378417 reply:
this is an arithmetic progression: 2,4,6,8,10... 100,
Summation formula: a1 + n * n (n - 1)/2 d

2 + 4 + 6 + 8... Tolerance of 2 + 100 is o the top 50 and arithmetic progression,
Using C language implementation is
Int a1=2;
Int n=50;
Int d=2;
Int a1 + sum=n * n * (n - 1) * d/2;
Printf (" sum=% d \ n ", sum);

When the input number is very big, this is faster than a for loop will be many,

This will be faster than the for loop,

It's a pity that a lot of people learn programming all learn silly! Forget the programming is for the sake of what

CodePudding user response:

I hope it can help you: https://blog.csdn.net/it_xiangqiang/category_10581430.html
I hope it can help you: https://blog.csdn.net/it_xiangqiang/category_10768339.html
  • Related