0

thank you for reading and hopefully responding to my question. I'm stuck trying to write this Python program that finds a number's square without using multiplication or exponents. Instead, I have to get the summation of the first odd n numbers starting from 1. This is what I have so far:

def square():
    print("This program calculates the square of a given number")
    print("WITHOUT using multiplication! ")
    odd = 1
    n = eval(input("Enter a number: "))
    for odd in range(0, n + 1, 2):
        odd = odd + 2 
        final_square = n + odd
    print(n, "squared is", final_square, ".") 

EDIT: Hi guys, I can't do 4 + 4 + 4 + 4. I have to do 1 + 3 + 5 + 7, and I'm not sure how. It gives me 4 squared is 11 or something.

Cœur
  • 37,241
  • 25
  • 195
  • 267
obtusefairy
  • 1
  • 1
  • 2

3 Answers3

1

Just some tips:

Try not to use eval(), it will evaluate any input given and so it can do something you don't want to do. Instead, use int().

Remember that, say 4*4, is just 4 + 4 + 4 + 4. You're on the right track with a for-loop, but now make the loop iterate n times adding n to itself.

new = 0
for _ in range(n):
    new += n

Note that this won't work with negative numbers. If you're going to be dealing with those, perhaps get the absolute value of n at the beginning:

def square(n):
    n = abs(n)
    ....
TerryA
  • 58,805
  • 11
  • 114
  • 143
1

Since you have been told you have to get the answer by producing the first n odd numbers, then you need to think about how to do that - certainly your loop isn't doing that :

several issues :

  1. you do odd =1, and then use odd in your for loop, the two can't co-exist, so the initial value of odd = 1 is overwritten.
  2. Your loop doesn't produce the first n odd numbers that I can see.

My suggest would be to rework your loop : the first 'n' odd numbers are in the form :

1, 3, 5, ... n*2-1 (Counting from 1 not from zero)

so a loop like this :

  final = 0 
  for c in range(1, n+1): #start counting from 1 to do 1 to n+1
      odd = c*2 -1        #Use the series above to generate each odd number.
      final += odd

should work

a much more 'pythonic' way to do this is :

 final = sum(c*2-1 for c in range(1,n))

This uses a generator to create all of the odd numbers (the equivalent of the loop), and sum the values as they get created.

Tony Suffolk 66
  • 9,358
  • 3
  • 30
  • 33
0

Go back to the original definition of multiplication.

Just add the number n to itself n times. What's so hard? It's inefficient has hell, but it'll work.

I'm sure there's a more Pythonic way:

def square(n):
   sum = 0
   for i in range(0,n):
      sum = sum + n
   return sum
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • The assignment appears to be not just to find the value of n**2, but to use the math trick that the sum of the first n odd numbers equals n**2. – PaulMcG Sep 16 '14 at 05:26