Last active
December 9, 2019 12:58
-
-
Save soscler/b164fd3061223f7f7164b19792e9e564 to your computer and use it in GitHub Desktop.
Compute the optimal spare money - With only coins of 2, bills of 5 and 10
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def impossible(n): | |
return n == 1 or n == 3 | |
def spare(m): | |
if impossible(m): | |
return ((0, 0, 0)) | |
# Compute the bills of 10 | |
pn10 = int(m / 10) | |
n10 = pn10 if not impossible(m - (pn10 * 10)) else pn10 - 1 | |
# Compute the bills of 5 | |
m = m - (n10 * 10) | |
pn5 = int(m / 5) | |
n5 = pn5 if not impossible(m - (pn5 * 5)) else pn5 - 1 | |
# Compute the coins of 2 | |
m = m - (n5 * 5) | |
pn2 = int(m / 2) | |
return (n10, n5, pn2) | |
if __name__ == '__main__': | |
m = int(input()) | |
n10, n5, n2 = spare(m) | |
print("Bill of 10: %d\nBill of 5: %d\nCoins of 2: %d" % (n10, n5, n2)) | |
""" A quick implementation in java | |
public class Change { | |
private long coins2 = 0; | |
private long bill5 = 0; | |
private long bill10 = 0; | |
private static boolean impossible(long n) { | |
return n == 1 || n == 3; | |
} | |
private static Change change(long m) { | |
Change change = new Change(); | |
if(impossible(m)) | |
return change; | |
// Compute the bills of 10 | |
long pn10 = m / 10; | |
long n10 = !impossible(m - (pn10 * 10))? pn10 : pn10 - 1; | |
// Compute the bills of 5 | |
m = m - (n10 * 10); | |
long pn5 = m / 5; | |
long n5 = !impossible(m - (pn10 * 5))? pn5 : pn5 - 1; | |
// Compute the coins of 2 | |
m = m - (n5 * 5); | |
long pn2 = m / 2; | |
change.bill10 = n10; | |
change.bill5 = n5; | |
change.coins2 = pn2; | |
return change; | |
} | |
public static void main(String[] args) { | |
Change change = Change.change(17L); | |
System.out.printf("Bill of 10: %d\nBill of 5: %d\nCoins of 2: %d" , change.bill10, change.bill5, change.coins2); | |
} | |
} | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment