THE QUESTION IS:
In a country called Chef Land, there was a lot of monetary fraud, so Chefu, the head of the country, decided to choose new denominations of the local currency ― all even-valued coins up to an integer N should exist. After a few days, a citizen complained that there was no way to create an odd value, so Chefu decided that he should also introduce coins with value 1. Formally, you are given an integer N; for v=1 and each even positive integer v≤N, coins with value v exist.
You are also given an integer S. To handle transactions quickly, find the minimum number of coins needed to pay a price S.
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains two space-separated integers S and N.
Output
For each test case, print a single line containing one integer ― the minimum number of coins.
Constraints
1≤T≤10,000
1≤S≤109
2≤N≤109
N is even
Subtasks
Subtask #1 (100 points): original constraints
Example Input
4
2 2
1 14
30 10
31 4
Example Output
1
1
3
9
MY SOLUTION IS
n=int(input())
res=[]
for i in range(1,n+1):
S,N = [int(x) for x in input().split()]
rem=S%N
if rem == 0:
res.append(int(S/N))
else:
if rem==1:
res.append(int(S/N+1))
else:
if rem/2 == 0:
res.append(int(S/N+1))
else:
res.append(int(S/N+2))
for j in res:
print(j)
Its showing my answer is wrong. Can anyone help me ?
Actually, I was not considering the case of getting 1 as a remainder i.e. in case of numbers like 31,41,51 etc. Which was causing me trouble. Well, after considering the above condition and some little manipulation it finally worked. Hope you understand it. And thank you for your responses.
n=int(input())
res=[]
for i in range(n):
S,N = [int(x) for x in input().split()]
rem=S%N
if S==1:
res.append(int(1))
elif(rem == 0):
res.append(int(S/N))
else:
if(rem%2==0 or rem==1):
res.append(int(S/N+1))
else:
res.append(int(S/N+2))
for j in res:
print(j)
Related
The output shows a different result. Yes, the factorials of those numbers are right but the numbers outputted aren't right.
Here's the code:
input:
n = int(input("Enter a number: "))
s = 0
fact = 1
a = 1
for i in range(len(str(n))):
r = n % 10
s += r
n //= 10
while a <= s:
fact *= a
a += 1
print('The factorial of', s, 'is', fact)
Output:
Enter a number: 123
The factorial of 3 is 6
The factorial of 5 is 120
The factorial of 6 is 720
You're confusing yourself by doing it all in one logic block. The logic for finding a factorial is easy, as is the logic for parsing through strings character by character. However, it is easy to get lost in trying to keep the program "simple," as you have.
Programming is taking your problem, designing a solution, breaking that solution down into as many simple, repeatable individual logic steps as possible, and then telling the computer how to do every simple step you need, and what order they need to be done in to accomplish your goal.
Your program has 3 functions.
The first is taking in input data.
input("Give number. Now.")
The second is finding individual numbers in that input.
for character in input("Give number. Now."):
try:
int(character)
except:
pass
The third is calculating factorials for the number from step 2. I won't give an example of this.
Here is a working program, that is, in my opinion, much more readable and easier to look at than yours and others here. Edit: it also prevents a non numerical character from halting execution, as well as using only basic Python logic.
def factorialize(int_in):
int_out = int_in
int_multiplier = int_in - 1
while int_multiplier >= 1:
int_out = int_out * int_multiplier
int_multiplier -= 1
return int_out
def factorialize_multinumber_string(str_in):
for value in str_in:
print(value)
try:
print("The factorial of {} is {}".format(value, factorialize(int(value))))
except:
pass
factorialize_multinumber_string(input("Please enter a series of single digits."))
You can use map function to get every single digit from number:
n = int(input("Enter a number: "))
digits = map(int, str(n))
for i in digits:
fact = 1
a = 1
while a <= i:
fact *= a
a += 1
print('The factorial of', i, 'is', fact)
Ok, apart from the fact that you print the wrong variable, there's a bigger error. You are assuming that your digits are ever increasing, like in 123. Try your code with 321... (this is true of Karol's answer as well). And you need to handle digit zero, too
What you need is to restart the calculation of the factorial from scratch for every digit. For example:
n = '2063'
for ch in reversed(n):
x = int(ch)
if x == 0:
print(f'fact of {x} is 1')
else:
fact = 1
for k in range(2,x+1):
fact *= k
print(f'fact of {x} is {fact}')
Lately am trying to do some Python programming, so am doing some mathematical exercices in some website.
I came across this example and at first I didn't understand the exercise. So I checked the solution to at least understand the question. As a consequence I found myself learning some coding tricks (like the while True loop).
The exercise is simple:
Write a Python program to find the smallest multiple of the first n numbers. Also, display the factors.
Below is the code:
def smallest_multiple(n):
if (n<=2):
return n
i = n * 2
factors = [number for number in range(n, 1, -1) if number * 2 > n]
print(factors)
while True:
for a in factors:
if i % a != 0:
i += n
break
if (a == factors[-1] and i % a == 0):
return i
My questions are:
Why does he create a list of numbers that are superior to the input by a factor of 2?
And then the while loop is just difficult to undestand. Could someone please explain it to me (I mean the content of the loop)?
I think we have here a tiny mixture of mathematic question and programming.
first of all, please note that the spaces are important in coding. see how the code should look like. (with the spaces)
def smallest_multiple(n):
if (n<=2):
return n
i = n * 2
factors = [number for number in range(n, 1, -1) if number * 2 > n]
print(factors)
while True:
for a in factors:
if i % a != 0:
i += n
break
if (a == factors[-1] and i % a == 0):
return i
1- Why does he create a list of numbers that are superior to the input by a factor of 2 ?
Answer : because the numbers that have their double smaller than the highest number will not affect / change the result. (This is a maths question) you can check that by removing the condition and you will see that you will get the same result (same smallest multiple)
2-And then the while loop is just difficult to understand. Could someone please explain it to me (I mean the content of the loop)? Thanks for your response?
Answer : The loop is using the boolean True as the code will only stops until it finds the smallest multiple for the first n numbers. the reason of the coder doing this because he has used the keyword return that will help him to exit the function, ultimately exiting the while loop.
The loop uses the value i which is the first multiple of the highest number of the first n numbers, meaning the double of the value n. Then will check if this first multiple (meaning i) is not dividable (i % a != 0) by the numbers in the list starting from the highest.
if i % a != 0:
i += n
break
this condition is there to increase the value of i as soon as i is not dividable by any number of the first n numbers meaning that the code keeps searching through the multiples of n (n being the highest number of the list) until i is dividable by all the numbers in the list
once the i value is able to satisfy the condition below
if (a == factors[-1] and i % a == 0):
then the while loop is exited through the keyword return which exits the function and the i value is sent as a response to the function call through the line return i
also note that factors[-1] is the last item (number) of the list.
I hope the above make sense and is clear to you.
p=[]
l=[]
v="run"
a=int(input("enter num or end: "))
while v!="end":
l.append(int(a))
a=input("enter num or end: ")
v=a
for a in l:
f=0
for j in range(2,a//2):
if a%j == 0:
f=1
break
if f==0:
p.append(a)
here I am inputting numbers and if its a prime number then I am putting it to list 'p' and at last output p.
i cant understand why 1st if statement not working when I am providing an even number like in picture below 4 is inputed so it should have changed value of f to 1 so that it doesn't get into list 'p' but its not. i am very new to python so there is possibility of silly mistakes.
on left code, on right output
The issue is that range(2, 4//2) is an empty range, since 4//2 = 2, and range(2, 2) includes every integer less than 2, starting with 2 - which is to say, no integers.
You will not have this issue with test numbers greater than 4, since in those cases you will always have at least 2 in the range of potential factors that you're testing.
It is because for 4 your statement:
for j in range(2, n//2):
becomes for j in range(2,2). if you have the same start and end in a range it does nothing. So it does not do the a % j and does not change f. In any case, if you are trying to check whether it is a prime number the range should be (2, int(n**0.5))
I tackled a beginners' exercise:
"asks the user for a number and then prints out a list of all the divisors of that number."
NB - I reviewed similar questions in this forum but decided to post the following as they didn't address
my needs.
The workflow I established is:
input an integer number, say x
add a variable which value is x/2, say y
declare a divisors list
if the x is greater than 4
iterate between 2 and y+1
if the remainder is zero
append it the the divisors list
if divisors list is empty or if the input number is smaller than 4
return: this is a primary number.
else, return divisors list
I ended up with the following solution. It does the job, but isn't good enough, as it has the following issues:
What is the python's input number limit? Currently, I have no limit which is wrong as it beyond the computational capacities of any computer.
I suspect my else statement isn't tidy enough. It can be shorter... but how?
If the number is lower than 4, the script returns twice the message "the number you entered is a primary number". I could fix it with an ad-hoc solution - but it should be solved through an algorithm not in a manual manner (...at least if I try to learn coding).
I ended up iterating in range of 2 and y+2 rather y+1 as I thought. I solved it manually but I don't understand why it isn't y+1.
num = int(input("Please select a number between: "))
y = num/2
if not y==0:
y=int(y-0.5)
list_range = list(range(2,y+2))
divisors_list = []
if num < 4:
print("The number you entered is a primary number")
else:
for i in list_range:
if num%i ==0:
divisors_list.append(i)
if not divisors_list:
print("The number you entered is a primary number")
else:
print(divisors_list)
Thanks for your consideration.
Have a little problem. I'm writing a simple program that takes an input of numbers (for example, 1567) and it adds the odd numbers together as well as lists them in the output. Here is my code:
import math
def oddsum(n):
y=n%10
if(y==0):
return
if(y%2!=0):
oddsum(int(n/10))
print (str(y),end="")
print (" ",end="")
else:
oddsum(int(n/10))
def main():
n=int(input("Enter a value : "))
print("The odd numbers are ",end="")
oddsum(n)
s = 0
while n!=0:
y=n%10
if(y%2!=0):
s += y
n //= 10
print("The sum would be ",end=' ')
print("=",s)
return
main()
It outputs just fine, in the example it will print 1 5 and 7 as the odd numbers. However, when it calculates the sum, it just says "7" instead of 13 like it should be. I can't really understand the logic behind what I'm doing wrong. If anyone could help me out a bit I'd appreciate it :)
I understand it's an issue with the "s += y" as it's just adding the 7 basically, but I'm not sure how to grab the 3 numbers of the output and add them together.
As #Anthony mentions, your code forever stays at 156 since it is an even num.
I would suggest you directly use the string input and loop through each element.
n = input("Enter a value : ") #'1567'
sum_of_input = sum(int(i) for i in n if int(i)%2) #1+5+7=13
[print(i, end="") for i in n if int(i)%2] #prints '157'
Note that int(i)%2 will return 1 if it is odd.
1567 % 10 will return 7. You might want to add the numbers you printed in oddsum to a list, and use the sum function on that list to return the right answer.
The immediate issue is that n only changes if the remainder is odd. eg 1,567 will correctly grab 7 and then n=156. 156 is even, so s fails to increment and n fails to divide by 10, instead sitting forever at 156.
More broadly, why aren't you taking advantage of your function? You're already looping through to figure out if a number is odd. You could add a global parameter (or just keep passing it down) to increment it.
And on a even more efficient scale, you don't need recursion to do this. You could take advantage of python's abilities to do lists. Convert your number (1567) into a string ('1567') and then loop through the string characters:
total = 0
for c in '1567':
c_int = int(c)
if c_int%2!= 0:
total += c_int
print(c)
print(total)