Question: You are given a number N and find the sum of the first N odd and even numbers in a line separated by space. All even and odd numbers should be greater than 0.
I think the problem asks to get the sum of all odd and even numbers uptil 2*n, but first of all, if you have started iterating from 1, why do you have a condition for i > 0 ??
things will be more clear when you link your submission and problem
You are given a number NN and find the sum of the first NN odd and even numbers in a line separated by space. All even and odd numbers should be greater than 00.
Input:
First-line will contain the number NN.
Output:
Print the sum of the first NN odd and even numbers in a line separated by space.
Constraints
1≤N≤1061≤N≤106
Sample Input 1:
4
Sample Output 1:
16 20
Sample Input 2:
1
Sample Output 2:
1 2
EXPLANATION:
In the first example, (1 + 3 + 5 + 7) = 16 and (2 + 4 + 6 + 8) = 20.
In the second example, only one odd that is 1 and only one even that is 2.
Given that N is as large as 10^6. Before getting into your solution, let’s try some examples.
N = 10
Odd = 100
Even = 110
Another example
N = 1000000
Odd = 1000000000000
Even = 1000001000000
(If you didn’t know the formula)
Odd = N * N
Even = N * (N + 1)
Now, talking about the constraints, the answer is as large as 10^{12}.
So, int, whose range is limited to about 2 \times 10^9, will not be sufficient to store this big value.
Hence, you have to use a bigger data type (usually long or long long).
In case you haven’t followed the entire explanation, here’s the code for you.
Your code, modified
#include <bits/stdc++.h>
using namespace std;
int main() {
int n = 0;
cin >> n;
long long int odd_sum = 0, even_sum = 0;
for(int i = 1; i <= 2 * n; i++) {
if(i % 2 == 0) {
even_sum += i;
}
else {
odd_sum += i;
}
}
cout << odd_sum << " " << even_sum << '\n';
return 0;
}
Usual style others prefer
#include <bits/stdc++.h>
using namespace std;
int main() {
long long int n = 0;
cin >> n;
long long int odd_sum = 0, even_sum = 0;
odd_sum = n * n;
even_sum = n * (n + 1);
cout << odd_sum << " " << even_sum << '\n';
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
long long es=0;
long long os=0;
int count=0;
for(int i=2;count<n;++i)
{
if(i%2==0)
{
es=es+i;
count++;
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
long long es=0;
long long os=0;
int count=0;
for(int i=2;count<n;++i)
{
if(i%2==0)
{
es=es+i;
count++;
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
long long es=0;
long long os=0;
int count=0;
for(int i=2;count<n;++i)
{
if(i%2==0)
{
es=es+i;
count++;
}
}
count=0;
for(int i=1;count<n;++i)
{
if(i%2!=0)
{
os=os+i;
count++;
}
}
cout<<os<<" "<<es<<endl;
}