here given the number 'n' we have find the sum of the even positive numbers before it. For that I tried to put a while loop in a for loop,but looks like that wont work
#include<iostream>
using namespace std;
int main() {
int n;
cin>>n;
int sum=0;
for(int counter=1;counter<=n;counter )
while(counter%2==0) {
sum=sum counter;
}
cout<<sum<<endl;
return 0;
}
CodePudding user response:
First off, I'd highly recommend incorporating some sort of UI, as it'll help you keep track of what's going on as your programs grow in complexity:
cout << "Enter an integer, and I will calculate the sum of all its preceding, positive integers: ";
And you'd need to swap that "while" for an "if". Reason being, you're adding to the sum, IF the counter's value is even:
for(int counter=1; counter<=n; counter ){
if(counter%2==0){
sum=sum counter;
}
}
Hope that helps!
CodePudding user response:
You probably want:
for(int counter=1;counter<=n;counter )
if(counter%2==0) // this is an if condition, not another loop
{
sum=sum counter;
}
CodePudding user response:
Rather than iterating over numbers, we can solve this in O(1) time complexity
.
Notice that sum of even numbers before a number N, forms an Arithmetic progression with 2 as first term, common difference 2 and number of terms ⌊N/2⌋
Sum = 2 4 6 ... N
Sum = 2(1 2 3 ... N/2)
Sum = 2((n)*(n 1)/2)
Sum = n*(n 1)
where n = ⌊N/2⌋
#include <iostream>
using namespace std;
int main() {
int N
cin>>N;
N = max(0, N);
long n = N/2;
long sum = n*(n 1);
cout<<sum<<endl;
return 0;
}