How do I create a code that prints out all the integers less than 100 that are not a square of any integer?
For instance, 3^2=9 to not be printed, but 30 should.
I’ve managed to print out the squared values but not sure how to print out the values that are not a square.
Here is my code:
for i in range(1,100):
square = i**2
print(square)
There can be multiple ways you can write this code. I think you can use two for loops here to make it easier for you. I'm using comments so for you being a newbie to understand better. You can choose from these two whichever you find easier to understand:
list_of_squares = [] #list to store the squares
for i in range(1, 11): #since we know 10's square is 100 and we only need numbers less than that
square = i ** 2
list_of_squares.append(square) #'append' keeps adding each number's square to this list
for i in range(1, 100):
if i not in list_of_squares: #'not in' selects only those numbers that are not in the squares' list
print(i)
Or
list_of_squares = []
for i in range(1, 100):
square = i ** 2
list_of_squares.append(square)
if square >= 100: #since we only need numbers less than 100
break #'break' breaks the loop when square reaches a value greater than or equal to 100
for i in range(1, 100):
if i not in list_of_squares:
print(i)
You can store the nums that is square of integers into a array.
squares =[]
for i in range(1,100):
squares.append(i**2)
j = 0
for k in range(1,100):
if k==squares[j]:
j=j+1
elif k>squares[j]:
print(k)
j=j+1
else:
print(k)
Related
I am trying to solve this problem: Goldbach Conjecture
Show with a program "goldbach.py" that all even numbers up to 1000 can indeed be written as the sum of two primes. Specifically: for each even number, also show explicitly (on the screen) that it can be written as the sum of two primes, as in the example below
Even more important is of course if you find a number that does not meet Goldbach's suspicion. Make sure your program clearly displays such a discovery on the screen. Bingo!
python goldbach.py
16 = ...
18 = 5 + 13
20 = 3 + 17
22 = 5 + 17
24 = ...
Progress
So far, I have created a list where all the primes until 1000 are stored, and then I have created a list in which all the combination of primes of which the sum is an even number until 1000. I knew the format to have it print 3 + 17, but I am stuck in trying to have it say sum(pairs) = prime1 "+" prime2. Should be 3 + 17 = 20 for example. Also, I don't know how to have only 1 example of a pair of primes who's sum is of an even number until 1000. I need to break the loop some how.
Because the sum function was not working I found I could convert it to a "numpy array" and then use "accumulate". I just can't get it to work and know I'm getting the error message 'DeprecationWarning: elementwise == comparison failed; this will raise an error in the future.'
Could someone help me with the code?
from itertools import accumulate, islice
from numpy import array
import numpy as np
primes = []
pairs = []
numpy_pairs = np.asarray(pairs)
for num in range (4, 1000):
for j in range (2, num):
if (num % j) == 0:
break
else:
primes.append(num)
#for x in range(2,1000):
# if x in primes:
# print ("Ja, het getal {} komt voor in mijn primes".format(x))
for x in range(2,1000):
if x % 2 == 0:
for prime1 in primes:
for prime2 in primes:
if prime1 + prime2 == x and [prime1, prime2] not in numpy_pairs and [prime2, prime1] not in numpy_pairs:
np.append(numpy_pairs,[prime1,prime2])
results = ("{}+{}={}".format(i, j, k) for i, j in zip(numpy_pairs[0::2],
numpy_pairs[1::2]) for k in accumulate(islice(numpy_pairs,numpy_pairs.stop)))
print('\n'.join(results))
First things first, there are a lot of optimizations you can do to make the code logic better. the way you find primes can be improved, you only need to check numbers upto square root n to verify if n is a prime. Also, the actual verification of Goldbachs conjecture can be improved as well.
However, just focusing on the current code, You should stick to using lists if you want to append values, and to stop the code you need to use a sort of hack to stop the nested looping using the for-else syntax. Also, you can use f-strings to format strings nicely from python 3.6 onwards.
primes = []
pairs = []
for num in range (2, 1000): #modified. you forgot 2 and 3!
for j in range (2, num):
if (num % j) == 0:
break
else:
primes.append(num)
result = []
for x in range(2,1000):
if x % 2 == 0:
for prime1 in primes:
for prime2 in primes:
if prime1 + prime2 == x:
print(f"{x} = {prime1} + {prime2}")
result.append((prime1, prime2))
break
else: #this is a for-else syntax. enter this block if the for loop did not encounter a break
continue #go to next iteration of the mid-level loop. This prevents the line afterwards from being executed in cases where the inner loop did not "break"
break #break the mid level loop if you reach this line.
else:
print("You have done it! Bingo!!")
I have this python problem:
Write a program that asks the user for a limit, and then prints out
the sequence of square numbers that are less than or equal to the
limit provided.
Max: 10
1
4
9
Here the last number is 9 because the next square number (16) would be
greater than the limit (10).
Here is another example where the maximum is a square number:
Max: 100 1
4
9
16
25
36
49
64
81
100
But I don't exactly know how to do this. So far I have
maximum = int(input("Max: "))
for i in range(1, maximum):
But don't really know how to process the numbers and squaring them.
Thanks
Edit: I have
maximum = int(input("Max: "))
for i in range(1, maximum):
if i*i <= maximum:
print(i*i)
'''
Ask the user input a limit and
convert input string into integer value
'''
limit = int(input("Please input the limit: "))
'''
Extract the squre root of `limit`.
In this way we discard every number (i) in range [0, limit]
whose square number ( i * i ) is not in range [0, limit].
This step improves the efficiency of your program.
'''
limit = int(limit ** .5)
'''
`range(a, b)` defines a range of [a, b)
In order to exclude zero,
we assign `a = 1`;
in order to include `limit`,
we assign `b = limit + 1`;
thus we use `range(1, limit + 1)`.
'''
for i in range(1, limit + 1):
print(i * i)
I think a while loop may be better suited for this problem.
maximum = int(input("Max: "))
i = 1
while(i*i <= maximum):
print(i*i)
i+=1
First, the simplest change to your existing code is to get rid of that nested loop. Just have the for loop and an if:
for i in range(1, maximum+1):
if i*i > maximum:
break
print(i*i)
Or just have the while loop and increment manually:
i = 1
while i*i <= maximum:
print(i*i)
i += 1
One thing: Notice I used range(1, maximum+1)? Ranges are half-open: range(1, maximum) gives us all the numbers up to but not including maximum, and we need to include maximum itself to have all the numbers up to maximum squared, in case it's 1. (That's the same reason to use <= instead of < in the while version.
But let’s have a bit more fun. If you had all of the natural numbers:
numbers = itertools.count(1)
… you could turn that into all of the squares:
squares = (i*i for i in numbers)
Don’t worry about the fact that there are an infinite number of them; we’re computing them lazily, and we’re going to stop once we pass maximum:
smallsquares = itertools.takewhile(lambda n: n<=maximum, squares)
… and now we have a nice finite sequence that we can just print out:
print(*smallsquares)
Or, if you’d prefer if all on one line (in which case you probably also prefer a from itertools import count, takewhile):
print(*takewhile(lambda n: n<=maximum, (i*i for i in count(1)))
But really, that lambda expression is kind of ugly; maybe (with from functools import partial and from operator import ge) it’s more readable like this:
print(*takewhile(partial(ge, maximum), (i*i for i in count(1)))
You got a few good, detailed answers.
But let's also have some fun, here is a one-line solution:
print(*(x**2 for x in range(1, 1 + int(int(input('Limit: '))**(1/2)))))
I have decided to post the answer that works. Thanks all for the help.
maximum = int(input("Max: "))
for i in range(1, maximum + 1):
if i*i <= maximum:
print(i*i)
THE BELOW PROGRAM IS TO FIND SQUARE VALUE OF GIVE NUMBERS
Enter the value you want to find.(Give a range)
the value you give runs and goes to r command.
i have used for loop in this case.
output will be displayed
give the input
maximum = input("Enter Max: ")
r = range(1, maximum)
Square = maximum * maximum
Execute THE loop
for i in r:
if i * i <= Square:
print (i * i),
I was trying to make a program which would check a number for its greatest prime factor. I was almost done when this error message came up. list index out of range.
What does this mean and what is wrong with my code?
Here is my code.
def is_prime(n):
for i in range(3, n):
if n % i == 0:
return False
return True
def Problem3():
x = 144
n = 2
not_a_factor = []
z = []
prime = []
not_a_prime = []
while n < x:
if x%n == 0:
z.append(n)
else:
not_a_factor.append(n)
n = n + 1
for i in z:
if is_prime(z[i]) == True:
prime.append(z[i])
else:
not_a_prime.append(z[i])
print(prime)
Problem3()
You're just a bit off. for-loops in Python iterate an object and return it's entities, not a pointer/ index.
So just use the thing you get from each iteration of 'z'
(Side note: might want to check out this post, it'll help you make your is_prime function more performant)
def is_prime(n):
for i in range(3, n):
if n % i == 0:
return False
return True
def Problem3():
x = 144
n = 2
not_a_factor = []
z = []
prime = []
not_a_prime = []
while n < x:
if x%n == 0:
z.append(n)
else:
not_a_factor.append(n)
n =+ 1 # Python version of n++
for i in z: # Python for-loop is more like a say "for each", no need for the indexing
if is_prime(i): # no need for '=='; Python will 'truthify' your object
prime.append(i)
else:
not_a_prime.append(i)
print(prime)
Problem3()
"list index out of range - what does this mean?"
The message list index out of range refers to an IndexError. Basically, this means that you are attempting to refer to an index in a list that doesn't exist.
Using your code as an example: you generate a list, z, containing the factors of the number 144. You then iterate through each element in this list (for i in z:). This means that for the:
1st iteration: i is the 1st element in z, which is 2;
2nd iteration: i is the 2nd element in z, which is 3;
and so on.
Then, you attempt if isprime(z[i]) == True:. So, as written, your program works like this:
1st iteration: if isprime(z[2]) == True:;
2nd iteration: if isprime(z[3]) == True:;
...
8th iteration: if isprime(z[16]) == True:
At this point, your code prompts an IndexError, because there are only 13 elements in z.
"what is wrong with my code?"
One way to get the result that you want is to iterate through range(len(z)) instead of each element of z. So, adjust the line for i in z to for i in range(len(z)).
Additionally, since prime is a list, and you want to return the greatest prime factor, change print(prime) to print(max(prime)).
These two changes will give you the result you are looking for.
Additional Learnings
Overall, your program could be written much more efficiently. If you want a simple algorithm to determine the greatest prime factor of a number, here is one possibility:
def greatest_prime_factor(n):
greatest_prime = 1
for i in range(n + 1):
# iterate through range(n). We skip index 0.
if i == 0:
continue
# determine if the number i is a factor of n.
if n % i == 0:
# determine if the number i is prime.
for i_ in range(2,i):
if i % i_ == 0:
break
else:
# update greatest_prime.
greatest_prime = max(greatest_prime, i)
return greatest_prime
print (greatest_prime_factor(144))
This algorithm saves a lot of memory space when compared with your original program by not initializing lists to store numbers that are primes, that aren't primes, etc. If you want to store those values, that's up to you; there are just far more efficient possibilities for what you appear to want to achieve.
Check this link for some more info on algorithmic efficiency and how to think about time and space complexity.
I've created a function which, hopefully, creates a list of numbers that are both pentagonal and square.
Here is what i've got so far:
def sqpent(n):
i = 0
list = []
while n >= 0:
if n == 0:
list.append(0)
elif n == 1:
list.append(1)
elif (i*i == (i*(3*i-1)//2)):
list.append(i)
n -= 1
i += 1
But when it gets past the first two numbers it seems to be taking a while to do so...
You have two issues: the first is that the special-casing for n==0 and n==1 doesn't decrease n, so it goes into an infinite loop. The special-casing isn't really needed and can be dropped.
The second, and more significant one, is that in the test i*i == (i*(3*i-1)//2) you are assuming that the index i will be the same for the square and pentagonal number. But this will only happen for i==0 and i==1, so you won't find values past that.
I suggest:
Iterate over i instead of n to make things simpler.
Take the ith pentagonal number and check if it is a square number (e.g. int(sqrt(x))**2 == x).
Stop when you've reached n numbers.
Thanks to #interjay's advice, I came up with this answer which works perfectly:
import math
def sqpent(n):
counter = 0
i = 0
l = []
while counter < n:
x = (i*(3*i-1)//2)
#print(x)
if(int(math.sqrt(x))**2 == x):
#print("APPENDED: " + str(x))
l.append(x)
counter += 1
i += 1
return l
For an explanation:
It iterates through a value i, and gets the ith pentagonal number. Then it checks if it is a square and if so it appends it to a list which i ultimately return.
It does this until a final point when the counter reaches the number of items in the list you want.
a = []
for i in range(3):
a.append(input())
j = 0
for i in a:
if i % 10 != 7:
j = min(a)
print j
I need an algorithm which finds the smallest positive number in list, which decimal representation does not end with the number 7. It is guaranteed that the list has at least one positive element, which decimal representation does not end with the number 7. I tried this, but condition doesn't work. For example: it says that 7 is smallest in [9,8,7].
You are always testing for the minimum number in a, albeit as many times as there are unfiltered numbers in a. Don't add numbers that end in 7 to a in the first place; you probably want to filter on positive numbers too:
a = []
for i in range(3):
value = input()
if i % 10 != 7 and i >= 0:
a.append(value)
print min(a)
Alternatively, filter out values in a generator expression:
a = []
for i in range(3):
a.append(input())
print min(i for i in a if i % 10 != 7 and i >= 0)
EDIT:
Ok I misreaded your code, you were using remainder which i think is better. Although it could work using just plain divisions like this.
if ((i / 10) - int(i / 10)) * 10 != 7:
And also, if you aren't using Python 3, you might need to use this for the above to work:
from __future__ import division
Or casting to floats with float(), but that makes it too messy.