Sum the n odd terms ,using Loop for ,without using list, allowed functions:input,int,print and range

Asked

Viewed 1,030 times

3

n =(int(input("Digite o número de termos:")))

for i in range(n+n):
    if i%2>0:
      print(i)     

#Não sei como prosseguir depois,como pego esses valores e somo eles 
  • O for shall be mounted as follows <code>for i in range(1, n + 1)</code>. In addition a counter shall be implemented.

4 answers

6

A detail: in the title it is said that you want to add the "n odd terms", and in the code is the message "Digite o número de termos". Does that mean that n is the amount of odd numbers, right?

For example, if n for 5, Do you want to add up all the odd numbers from 1 to 5 (i.e., 1 + 3 + 5), or do you want to add up the first 5 odd numbers (i.e., 1 + 3 + 5 + 7 + 9)? The other answers understood that it is the first option...

Anyway, let’s see a solution for each:


Add the odd ones from 1 to n

If so, there are several options. It can be with a simple loop:

n = int(input("Digite o número de termos:"))
soma = 0
for i in range(1, n + 1, 2):
    soma += i
print(soma) # 9 (1 + 3 + 5)

Note that I use the third parameter of range, which is the step, that is, the increment that is added to each element to generate the next one. If the range begins in 1 and I just want the odd numbers, I can jump from 2 to 2. No need none to advance 1 by 1 and go testing whether the number is even or odd (unless it is an exercise that "demand" do this).

Also note that the range ends in n + 1, because the last number is not included (ie if I just put n, own n would not be added).

Another way to do it is to use sum, along with a Generator Expression, much more succinct and pythonic:

soma = sum(i for i in range(1, n + 1, 2))
print(soma)

Although sum receives an iterable parameter, and ranges are eternal, so you can simplify even more:

soma = sum(range(1, n + 1, 2))
print(soma)

Add up the n first odd numbers

If when n is, for example, equal to 5, and the goal is to add up the first 5 odd numbers (i.e., 1 + 3 + 5 + 7 + 9), there it is like this:

soma = 0
impar = 1
for i in range(n):
    soma += impar
    impar += 2
print(soma) # 25 (1 + 3 + 5 + 7 + 9)

The range(n) serves to control the amount of odd numbers, and the odd number starts at 1 and is incremented by 2 in 2.

The for above can also be more succinct:

soma, impar = 0, 1
for i in range(n):
    soma, impar = soma + impar, impar + 2

Although the nth odd number is equal to 2n - 1, then it would be enough to use similar solutions to the first case, but now using a range until 2n:

soma = 0
for i in range(1, 2 * n, 2):
    soma += i
print(soma)

# ou
soma = sum(range(1, 2 * n, 2))
print(soma)

But in fact this problem boils down to the sum of a PA (arithmetic progression), and in that case there is a ready-made formula for the sum of the first N terms:

(a1 + an) * n / 2
  • a1 is the first term (in our case it is 1)
  • an is the umpteenth term, which in turn is equal to a1 + (n - 1) * r (and r is the reason, that in our case is 2 - the difference between each term of PA)

So just apply the formula:

n = int(input("Digite o número de termos:"))

soma = (1 + 1 + (n - 1) * 2) * n / 2

But note that if you simplify the above formula with these specific values (a1=1 and r=2), will come to the conclusion that the sum of n first odd numbers is equal to n squared, then a more succinct way is still:

soma = n * n

# ou
soma = n ** 2

Note: the AP formula can also be applied for the first case (adding odd numbers from 1 to n). But in that case n is the nth term, and the quantity of terms shall be calculated:

# calcule a quantidade de termos
qtd = (1 + n) // 2

# use a fórmula da soma da PA
soma = (1 + n) * qtd / 2

# ou, como é a soma dos primeiros "qtd" ímpares, use a "fórmula simplificada"
soma = qtd ** 2

But if it’s an exercise that "requires" using a for 1 in 1 and also the operator %, then the solution is:

# soma dos ímpares de 1 a n
soma = 0
for i in range(1, n + 1):
    if i % 2 != 0:
        soma += i
print(soma)

# soma dos n primeiros ímpares
soma = 0
for i in range(1, 2 * n):
    if i % 2 != 0:
        soma += i
print(soma)

4

There are some problems, like your range that is increasing (doubling) the amount of terms:

range(n+n)

To get the values, just access the loop variable, you already do this, but just print the contents of it:

print(i)

To add the terms, you will need another variable, we will create it with the value of zero and call it sum, to be very evident your purpose:

soma = 0

In the for, we’ll use it from 1 to the end:

for i in range(1, n+1):

Now inside the for, let’s add the value in the variable soma whenever it is odd;

if i%2>0:
  soma += i

And finally, we only print the variable value soma:

print(soma)

Putting it all together, the code will look like this:

n = int(input("Digite o número de termos:"))
soma = 0

for i in range(1, n+1):
  if i%2 > 0:
    soma += i

print(soma)

See online: https://repl.it/repls/RashFortunateLevels

4

Here’s the solution. I don’t understand what you’re adding up to n + n?

n =(int(input("Digite o número de termos:")))

result = 0

for i in range(n):
  if not i % 2 == 0:
    result += i


print(result)

1

In this matter you have to pay attention to two things.

First thing:

Define an accumulating variable (variable that will store the calculation performed in each iteration of "for"). Variable that I will call "x".

Second thing:

Structure the for correctly.

If you intend to use the repeat loop "for", iterating over a range, you have to set the limits of this range. In this case, the for would look the way...

for c in range(1, n + 1):

...where "1" would be the lower limit and "n + 1" the upper limit.

With these two situations in mind, I developed the following algorithm below.

# Capturando e tratando o valor inserido no input.
while True:
    try:
        n = int(input('Digite o número de termos: '))
        if n <= 0:
            print('\033[31mValor INVÁLIDO! Digite apenas inteiros maiores que "0"!\033[m')
        else: 
            break
    except:
        print('\033[31mValor INVÁLIDO! Digite apenas números inteiros!\033[m')

# Realizando os cálculos e exibindo o resultado:
x = 0
for c in range(1, n + 1):
    if c % 2 != 0:
        x += c
print(f'O resultado é: {x}')

Note how the code works on Repl.it

Also note that this algorithm performs a treatment of the values captured by the input.

  • Just a hint: you don’t have to put one while inside the other. The while external already guarantees the repetition, just check the conditions and only call the break if the number is valid, thus: https://ideone.com/QoGGSr (another advantage is not having to repeat the call of input)

  • The function of the internal <code>while</code> is to restrict integer numbers smaller than <code>"0"</code>. Note that if you enter a value <code>less than "0"</code> the algorithm will not advance. The algorithm will only advance if the value is greater than <code>"0"</code> for this reason there is a need to implement this second <code>"while"</code>.

  • Did you see the link I passed? https://ideone.com/QoGGSr - it does the same thing, without needing the while intern :-)

  • Okay, I’ll take a look.

  • Yes, I understood your position. I think the only difference was only in the type of structure. You used "if" and I used a second "while". Thanks for the tip. Hug!

  • Well, another difference, as I said, is that you don’t need to repeat the call input twice - it may seem like a stupid detail, but if you want to change the message, for example, you would have to change in 2 places, already the way I did, just change in one place. Avoiding unnecessary repetition is something that can)

  • Ok. Your arguments actually proceed. In a large code the maintenance would be unfeasible. I will rectify the code.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.