-2

Assume there is a variable , h already associated with a positive integer value. Write the code necessary to count the number of perfect squares whose value is less than h , starting with 1 . (A perfect square is an integer like 9 , 16 , 25 , 36 that is equal to the square of another integer (in this case 3*3 , 4*4 , 5*5 , 6*6 respectively).) Assign the sum you compute to a variable q For example, if h is 19 , you would assign 4 to q because there are perfect squares (starting with 1 ) that are less than h are: 1 , 4 , 9 , 16 .

This is what I have so far, I can't figure out what I'm doing wrong.

q = 0

sqrt = int(h ** 0.5)

if sqrt != h:

h += 1

for i in range(1, sqrt):

q += 1

  • 1
    just calculate the value of floor(sqrt(h)). –  May 20 '14 at 02:56
  • 1
    Hint: int(h**0.5) *is* the number of perfect squares less than or equal to h. –  May 20 '14 at 02:56
  • Note that in general, `for i in range(1, n): q += 1` is identical to `q += n`. – Mark Dominus May 20 '14 at 03:03
  • You were probably meant to do this without using square roots; which make it trivial. Instead, try incrementing the value of $q$ from $0$ while $q\ast q$ is less than or equal to $h$. –  May 20 '14 at 03:09

2 Answers2

1
main:  
  q=-1  
  s=0  
  WHILE(s$\lt$h)  
    q=q+1  
    s=s+2*q+1  
    WEND  
    PRINT q  
END
secretformula
  • 6,414
  • 3
  • 33
  • 56
0

q = 0

sqrt = int(h ** 0.5)

if sqrt != h:

h += 1

for i in range(1, sqrt):

q += 1

This is bloated code.

  • Why are you incrementing h?
  • Why are you using a for loop to increment q?