Python: Closest Power of Two To Target - python

I am attempting to find the closest power of two that is greater than or equal to a target value. A for loop must be used to achieve this. However, I am unsure of what to put as the range value so that upon reaching the required value the exponent will stop increasing by i and instead exit the for loop. Thanks for your help.
target = int(input("Enter target number: "))
def power_of_two(target):
x = 2
change = 0
power = 0
for i in range():
number = x ** change
change = i
if number >= target:
power = number
return power
p = power_of_two(target)
print("The closest power of 2 >= {0:d} is {1:d}." .format(target, p))

since you have to use for:
def power_of_two(target):
if target > 1:
for i in range(1, int(target)):
if (2 ** i >= target):
return 2 ** i
else:
return 1
that is assuming you want the value to be greater than or equal to 2^0

I have corrected your code, so that it works. I think you learn best from your mistakes :)
target = int(input("Enter target number: "))
def power_of_two(target):
x = 2
change = 0
power = 0
for i in range(target+1):
# target is okay for this, function terminates anyway
# add one to avoid error if target=0
number = x ** change
change = i
if number >= target: # you had indentation errors here and following
power = number
return power
p = power_of_two(target)
print("The closest power of 2 >= {0:d} is {1:d}." .format(target, p))
You could find a perfect value for the end of the range using logarithm with base 2, but then you wouldn't need the for loop anyway ;)
As a suggestion: maybe take a look at the binary representation of powers of 2. You could use a for loop with bitshifting for this.
EDIT: I had indentation errors myself, because of the weird formatting system here... maybe you haven't had these before :D

Related

Sum of all prime numbers between 1 and N in Python

I'm new to programming. While trying to solve this problem, I'm getting the wrong answer. I checked my code a number of times but was not able to figure out the mistake. Please, help me on this simple problem. The problem is as follows:
Given a positive integer N, calculate the sum of all prime numbers between 1 and N (inclusive). The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains one line of input containing N. For each testcase, in a new line, print the sum of all prime numbers between 1 and N.
And my code is:
from math import sqrt
sum = 0
test = int(input())
for i in range(test):
max = int(input())
if max==1:
sum = 0
elif max==2:
sum += 2
else:
sum = sum + 2
for x in range(3,max+1):
half = int(sqrt(max)) + 1
for y in range(2,half):
res = x%y
if res==0:
sum = sum + x
break
print(sum)
For input 5 and 10, my code is giving output 6 and 48 respectively, while the correct answer is 10 and 17 respectively. Please, figure out the mistake in my code.
Here, I implemented simple program to find the sum of all prime numbers between 1 to n.
Consider primeAddition() as a function and ip as an input parameter. It may help you to solve your problem.Try it.
Code snippet:
def primeAddition(ip):
# list to store prime numbers...
prime = [True] * (ip + 1)
p = 2
while p * p <= ip:
# If prime[p] is not changed, then it is a prime...
if prime[p] == True:
# Update all multiples of p...
i = p * 2
while i <= ip:
prime[i] = False
i += p
p += 1
# Return sum of prime numbers...
sum = 0
for i in range (2, ip + 1):
if(prime[i]):
sum += i
return sum
#The program is ready... Now, time to call the primeAddition() function with any argument... Here I pass 5 as an argument...
#Function call...
print primeAddition(5)
This is the most broken part of your code, it's doing the opposite of what you want:
res = x%y
if res==0:
sum = sum + x
break
You only increment sum if you get through the entire loop without breaking. (And don't use sum as you're redefining a Python built-in.) This can be checked using the special case of else on a for loop, aka "no break". I've made that change below as well as corrected some inefficiencies:
from math import sqrt
T = int(input())
for _ in range(T):
N = int(input())
sum_of_primes = 0
if N < 2:
pass
elif N == 2:
sum_of_primes = 2
else:
sum_of_primes = 2
for number in range(3, N + 1, 2):
for odd in range(3, int(sqrt(number)) + 1, 2):
if (number % odd) == 0:
break
else: # no break
sum_of_primes += number
print(sum_of_primes)
OUTPUT
> python3 test.py
3
5
10
10
17
23
100
>
A slight modification to what you have:
from math import sqrt
sum = 0
test = int(input())
max = int(input())
for x in range(test,max+1):
if x == 1:
pass
else:
half = int(sqrt(x)) + 1
for y in range(2,half):
res = x%y
if res==0:
break
else:
sum = sum + x
print(sum)
Your biggest error was that you were doing the sum = sum + x before the break rather than outside in an else statement.
PS: (although you can) I'd recommend not using variable names like max and sum in your code. These are special functions that are now overridden.
Because your logic is not correct.
for y in range(2,half):
res = x%y
if res==0:
sum = sum + x
break
here you check for the factors and if there is a factor then adds to sum which is opposite of the Primes. So check for the numbers where there is no factors(except 1).
from math import sqrt
test = int(input())
for i in range(test):
sum = 0
max = int(input())
if max==1:
sum = 0
elif max==2:
sum += 2
else:
sum = sum + 2
for x in range(3,max+1):
half = int(sqrt(x)) + 1
if all(x%y!=0 for y in range(2,half)):
sum = sum + x
print(sum)
First of all, declare sum to be zero at the beginning of the for i loop.
The problem lies in the if statement at almost the very end of the code, as you add x to the sum, if the res is equal to zero, meaning that the number is indeed not a prime number. You can see that this is the case, because you get an output of 6 when entering 5, as the only non-prime number in the range 1 to and including 5 is 4 and you add 2 to the sum at the beginning already.
Last but not least, you should change the
half = int(sqrt(max)) + 1
line to
half = int(sqrt(x)) + 1
Try to work with my information provided and fix the code yourself. You learn the most by not copying other people's code.
Happy coding!
I believe the mistake in your code might be coming from the following lines of code:
for x in range(3,max+1):
half = int(sqrt(max)) + 1
Since you are looping using x, you should change int(sqrt(max)) to int(sqrt(x)) like this:
for x in range(3,max+1):
half = int(sqrt(x)) + 1
Your code is trying to see if max is prime N times, where you should be seeing if every number from 1-N is prime instead.
This is my first time answering a question so if you need more help just let me know.

Squaring numbers in a loop

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),

Hofstadter equation related code in python

There was this question in a university assignment related to Hofstadter sequence. It basically say that it is a integer sequence blah blah and there are two values for a given index n. A male value [M(n)] and a female value [F(n)].
They are defined as:
M(0)=0
F(0)=1
M(n)=n-F(M(n-1))
F(n)=n-M(F(n-1))
And we were asked to write a program in python to find the Male and Female values of the sequence of a given integer.
So the code I wrote was:
def female(num):
if num == 0:
return 1
elif num >0:
return num - male(female(num-1))
def male(num):
if num==0:
return 0
elif num >0:
return num - female(male(num-1))
And when executed with a command like
print male(5)
It works without a fuss. But when I try to find the value of n = 300, the program gives no output.
So I added a print method inside one of the functions to find out what happens to the num value
[ elif num>0:
print num ...]
And it shows that the num value is decreasing until 1 and keeps hopping between 1 and 2 at times reaching values like 6.
I can’t figure out why it happens. Any insight would be nice. Also what should I do to find the values relevant to bigger integers. Thanks in advance. Cheers.
The code is theoretically fine. What you underestimate is the complexity of the computation. Formula
M(n)=n-F(M(n-1))
actually means
tmp = M(n-1)
M(n) = n - F(tmp)
So if you represent this calculation as a tree of necessary calls, you might see that its a binary tree and you should go through all its nodes to calculate the results. Given that M(n) and F(n) are about n/2 I'd estimate the total number of the nodes to be of order 2^(n/2) which becomes a huge number once you put n = 300 there. So the code works but it just will take a very very long time to finish.
The one way to work this around is to employ caching in a form of memoization. A code like this:
femCache = dict()
def female(num):
#print("female " + str(num))
global femCache
if num in femCache:
return femCache[num];
else:
res = 1 # value for num = 0
if num > 0:
res = num - male(female(num-1))
femCache[num] = res
return res
maleCache = dict()
def male(num):
#print("male " + str(num))
global maleCache
if num in maleCache:
return maleCache[num];
else:
res = 0 # value for num = 0
if num > 0:
res = num - female(male(num-1))
maleCache[num] = res
return res
print(male(300))
should be able to compute male(300) in no time.

What makes this code so slow? (for project Euler q45)

I just solved and found the answer for problem 45 on project euler, however the solution took twenty minutes to compute. Other similar solutions take less than a second to find the solution.
The problem
My code:
import time
def is_triangular(n):
triangle_index = (((8 * n + 1) ** 0.5) + 1) / 2
if triangle_index % 1 == 0:
return True
return False
def is_pentagonal(n):
pentagonal_index = (((24 * n + 1) ** 0.5) + 1) / 6
if pentagonal_index % 1 == 0:
return True
return False
def is_hexagonal(n):
hexagonal_index = (((8 * n + 1) ** 0.5) + 1) / 4
if hexagonal_index % 1 == 0:
return True
return False
number = 40756
while True:
if is_triangular(number) and is_pentagonal(number) and is_hexagonal(number):
print(number)
break
number += 1
Instead of going through every number and checking if its triangular, pentagonal and hexagonal. Generate Hexagonal numbers and for each hexagonal number check if its triangular or pentagonal.
You can generate hexagonal numbers by using the formula for hexagonal numbers and increasing n by 1.
Because you are looking to every natural number after 40755. Limit the case to a subset of real numbers: if you know already that a number is not hexagonal you can discard it already, for example.
Since the hexagonals are in the less dense subset, start by looking to numbers in that set. Then, check if they're pentagonals, and eventually check if those are triangular too.
main function example:
hex = 144
while True:
number = hex*(2*hex-1)
if is_hexagonal(number):
if is_pentagonal(number):
if is_triangular(number):
print("Found: {}".format(number))
break
hex += 1
There are other modifications that can be done in the Python code, but I focused on the algorithm only.

Equal or higher multiple of a number, Python

I have been challenged with designing a code which validates a GTIN-8 code. I have looked on how to find the equal or higher multiple of a 10 and I have had no success so far, hope you guys can help me!
Here is a small piece of code, I need to find the equal or higher multiple of 10.
NewNumber = (NewGtin_1 + Gtin_2 + NewGtin_3 + Gtin_4 + NewGtin_5 + Gtin_6 + NewGtin_7)
print (NewNumber)
If you mean find the smallest multiple of 10 that is greater than or equal to your number, try
def round_up_by_10s(num):
return -((-num) // 10) * 10
That works for positive and negative numbers, integer or float, in Python 2.x or Python 3.x. It also avoids an if statement and can be written as a one-liner. For a float number it returns a float: surround the return value with an int(...) if you want the returned value to always be an integer.
If you mean find the smallest number that is a multiple of your number and of 10, try
def lcm10(num):
return (10 // gcd(num, 10)) * num
Generally speaking You can find multiples with the modulo operation:
if number % 10 == 0:
do something
I'm guessing you what the smallest multiple of 10 that is higher or equal than NewNumber. If that's the case, do:
last_digit = NewNumber % 10
bigger = NewNumber - last_digit
if last_digit != 0:
bigger += 10
Also, you shouldn't use capital letters to start variable names, those are usually used for classes only.
Trying using this:
# method 1 for integers
n = NewNumber / 10 * 10
if n < NewNumber: n += 10
# method 2 for floats, decimals
import math
n = math.ceil(NewNumber / 10) * 10

Categories

Resources