DEV Community

Cover image for Sum of first "n" odd numbers with Python
Saurabh Sharma
Saurabh Sharma

Posted on

Sum of first "n" odd numbers with Python

It is my first post so ignore any silly mistakes.
Moving onto the topic. As it says I am going to make a python program to find the sum of first “n” odd numbers starting with 1.
Now before you go into my while loop if you are here for quick result. Here is the easiest way to do it.

Alt Text

Now if you are wondering why the heck I print “square of number”, then you may need to go through basic mathematics. Alas! I am a coder man. So head to this WikiHow post.

Now coming back to problem. If you are still reading probably you also don’t like such silly and short method.
Welcome to a large solution. (Still small xD)

Alt Text

HA! Now comes my favourite (favorite if you are American 😄) part.

Step 1. We take input and convert it to integer. Cause that is string right?

Step 2. We define some variables. “i” is iterator which will tell when we have reached “n” numbers (If you forgot “n” is the number of odd numbers we have to add). The “current” variable is our sum of numbers which gets updated at every loop (the loop we will write in next step). Initially set to 1, cause that’s our first odd number in Mathematics. And finally we got our lovely variable for which we are writing this all, “sum”. By the way it also gets updated at every loop.

Step 3. We got our very own while loop. You know what it is right. It keeps on repeating itself until its argument is true. And that argument my readers is the boolean value of “ i < n ”.
Now it means when i becomes equal to n, we stop our loop cause we added them. And print the result. I know what you are thinking. The inner of loop.
Here we have “some” variable being incremented by the value of “current” variable. Which in first iteration is 1 (first odd number), after that we update our “current” variable to next odd number which always is +2, or am I wrong?
Next thing we do is increment our iterator cause without that you know it goes “to infinity and beyond”.
Hope you like it, cause even if you don’t I can do nothing.

Oldest comments (1)

Collapse
 
anatoliyaksenov profile image
Anatoliy A Aksenov

For thought:

# our input array
a = [1,10,6,7,8,9,11,12,2,3,4,5,13,18,14,15,16,17,19]
  • sums odd numbers by sorted input:
first_n = 4
sum([x for x in sorted(a) if x%2 != 0][:first_n])

or sums odd numbers by unsorted input

first_n = 4
sum([x for x in a if x%2 != 0][:first_n])
  • for even numbers
first_n = 4
sum([x for x in sorted(a) if x%2 == 0][:first_n])