Cheap Travel (466A) Problem from Codeforces - c++

Full problem: (from https://codeforces.com/problemset/problem/466/A)
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of money she will have to spend to make n rides?
Input
The single line contains four space-separated integers n, m, a, b (1 ≤ n, m, a, b ≤ 1000) — the number of rides Ann has planned, the number of rides covered by the m ride ticket, the price of a one ride ticket and the price of an m ride ticket.
Output
Print a single integer — the minimum sum in rubles that Ann will need to spend.
Solution from Codeforces (https://codeforces.com/contest/466/submission/7784793):
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n, m, a, b;
cin >> n >> m >> a >> b;
if (m * a <= b)
cout << n * a << "\n";
else
cout << (n/m) * b + min((n%m) * a, b) << "\n";
return 0;
}
Although I understand that the conditional statements check if there should be a special ride ticket bought or not, but how is the expression (m * a <= b) derived, and how it is useful in checking if there should be special tickets bought or not? Additionally, i understand how (n/m) * b) is derived, but min((n%m) * a, b) really confuses me.

if (m * a <= b) covers the nonsensical case (in the real world) where the special ticket is at least as expensive as regular tickets for the same number of journeys. Eg a=1, b=10, m=5. Here m * a <= b so it's cheaper to buy the regular tickets.
Having established that it might be worthwhile to buy the regular tickets you should buy (n/m) of them at a cost of (n/m) * b rubles. The remaining journeys could be paid for with one special ticket costing b rubles or with (n%m) regular tickets costing (n%m) * a rubles. Whichever of those is cheaper gives the formula min((n%m) * a, b).

Related

How to Calculate Compound Interest in C++?

I'm trying to write a program to calculate compound interest, but I'm not sure how to use the pow() function. My assignment is this:
Dvijesh makes his first $1,025.75 deposit into an IRA earning 4.125% compounded annually on his 24th birthday and his last $1,025.75 deposit on his 35th birthday. With no additional deposits, the money in the IRA continues to earn 4.125% interest compounded monthly until Dvijesh retires on his 65th birthday. Write a program to find out the amount of money that Dvijesh has in his IRA on his 35th and 65th birthday? How much interest did Dvijesh earn on his 35th and 65th birthday?
FV = PMT{(1+i)^n-1 / i}
A=P(1+i)^n
FV:Future Value; PMT:Periodic Payment; i:Rate Per Period; n:Number Of
Payments; A:Future Amount; P:Principal
Right now, I'm trying to calculate the first formula, and this is what I have so far:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double futureValue, periodic_payment, rate_per_period;
int n; // number of payments
cout << "Enter the periodic payment, rate per period, and time of investment: ";
cin >> periodic_payment >> rate_per_period >> n;
// Future value of 35th birthday
futureValue = periodic_payment * pow((1 + rate_per_period, n) * 0.01) / (rate_per_period));
return 0;
}
We wrote something similar in my C++ class, but the formula was different. I'm not sure how to write FV = PMT{(1+i)^n-1 / i} in C++.
pow() (and std::pow()) takes 2 input arguments, but you are passing in only 1 value - the result of this calculation:
(1 + rate_per_period, n) * 0.01
Because of your use of the comma operator, (1 + rate_per_period, n) returns n, thus the above is effectively just this simpler calculation:
n * 0.01
That is the sole value you are passing to pow(). But that is not what it wants.
The formula (1+i)^n-1 / i does not translate into this code, as you have written it:
pow((1 + rate_per_period, n) * 0.01)
It actually translates into code more like this instead:
pow(1 + rate_per_period, n - 1 / i)
or:
pow(1 + rate_per_period, n - 1) / i
or:
pow(1 + rate_per_period, n) - 1 / i
Depending on how you read the formula. However, those solutions are all wrong, because the formulas you have shown are written incorrectly to begin with! So, you are translating them into C++ code incorrectly.
The correct formula is:

How to make my CodeChef solution code faster?

I am a beginner currently in first semester. I have been practising on Code Chef and am stuck at this problem. They are asking to reduce the execution time of my code. The problem goes as follows:
Meliodas and Ban are fighting over chocolates. Meliodas has X chocolates, while Ban has Y. Whoever has lesser number of chocolates eats as many chocolates as he has from the other's collection. This eatfest war continues till either they have the same number of chocolates, or at least one of them is left with no chocolates.
Can you help Elizabeth predict the total no of chocolates they'll be left with at the end of their war?
Input:
First line will contain T, number of testcases. Then the testcases follow.
Each testcase contains of a single line of input, which contains two integers X,Y, the no of chocolates Meliodas and Ban have, respectively.
Output:
For each testcase, output in a single line the no of chocolates that remain after Ban and Meliodas stop fighting.
Sample Input:
3
5 3
10 10
4 8
Sample Output:
2
20
8
My code is as follows:
#include <iostream>
using namespace std;
int main()
{
unsigned int t,B,M;
cin>>t;
while(t--)
{
cin>>M>>B;
if(B==M)
{
cout<<B+M<<endl;
}
else
{
for(int i=1;B!=M;i++)
{
if(B>M)
B=B-M;
else
M=M-B;
}
cout<<M+B<<endl;
}
}
return 0;
}
Assuming that Band Mare different from 0, this algorithm corresponds to one version of the Euclidean algorithm. Therefore, you can simply:
std::cout << 2 * std::gcd(B, M) << "\n";
If at least one of the quantity is equal to 0, then just print B + M.
After realizing that your code was correct, I wondered where could be any algorithmic improvement. And I realized that eating as many chocolate from the peer as one has was in fact close to a modulo operation. If both number are close, a minus operation could be slightly faster than a modulo one, but if one number is high, while the other is 1, you immediately get it instead of looping a great number of times...
The key to prevent stupid errors is to realize that if a modulo is 0, that means that the high number is a multiple of the small one and we must stop immediately writing twice the lower value.
And care should be taken that if one of the initial counts are 0, the total number will never change.
So the outer loop should become:
if(B==M || B == 0 || M == 0)
{
cout<<B+M<<"\0";
}
else {
for (;;) {
if (M < B) {
B = B % M;
if (B == 0) {
cout << M * 2 << '\n';
break;
}
}
else {
M = M % B;
if (M == 0) {
cout << B * 2 << '\n';
break;
}
}
}
}
...
Note: no infinite loop is possible here because a modulo ensures that for example is M > B > 0' after M = M % Byou will haveB > M >= 0and as the case== 0` is explicitely handled the number of loops cannot be higher than the lower number.

My code is failing a test due to time limit restriction, how do I decrease the time taken by my code to work?

Question - You are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test cases.
Input -
The first line of the input contains one integer t (1≤t≤10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers a and b (1≤a,b≤10^9).
Output -
For each test case print the answer — the minimum number of moves you need to do in order to make a divisible by b.
Code Forces question link - https://codeforces.com/problemset/problem/1328/A
Time Limit - 1 second per test case
My code -
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
long long t,a,b,x;
cin >> t;
for(long long i=0;i<t;i++){
cin >> a >> b;
x = a;
while(a%b!=0){
a++;
}
cout << a-x << endl;
}
}
It is failing when the number of test cases is 10000 and there are big input numbers. What can I do to decrease the execution time of my code?
You need to find m such that a + m = kb with 0≤m<b (you want the next multiple). If we divide the equation by b, we have (a + m)/b = k, which is also k = ceiling(a/b).
So m = ceiling(a/b) b - a.

C++ Decrementing and displaying active equations

I'm looking at figuring out this program for a lab, I have been working on it for a while now, but cannot for the life of me figure out how this works.
The objective is to display an active equation as it decrements from from the initial value.
For example:
20000.00 + 83.33 - 150.00 = 19933.33
19933.33 + 83.06 - 150.00 = 19866.39
19866.39 + 82.78 - 150.00 = 19799.17
19799.17 + 82.50 - 150.00 = 19731.66
19731.66 + 82.22 - 150.00 = 19663.88
19663.88 + 81.93 - 150.00 = 19595.81
19595.81 + 81.65 - 150.00 = 19527.46
And so forth. I have to display that as an output on the screen. But am not sure how to keep a decrementing total like that and how to display it as an active equation like that in cout form.
The number on the far left is an initial loan that a user inputs, the number in the middle is the interest rate which is calculate using p*r/p (initial loan * interestrate(user will input this as well)/ initial loan). And the number on the right just before the equal sign is a payment which the usual will enter.
The goal is to get it to perform 10 iterations or once the initial loan is fully paid off whichever comes first.
Here is a little guidance
Finance
First you got your basics wrong. If this is finance and it looks this way :-), p*r/p is crap.
The second column in your plot is not a rate, neither is it an interest rate, it is an interest.
P is the loan ammount
r is an annual interest rate
The interest is calculated using P times r/12 since the payments you show are monthly in case r is entered mathematically (e.g. 0.05 for 5 %) or P*r/1200 in case r is counterconventional entered as percentage.
C++
The input of the parameters could be done e.g.
double P, r, q;
std::cout << "Enter P, q and r:\t";
std::cin >> P >> r >> q;
you will need to have the numbers printed fixed precision, this can by done with
std::cout << std::fixed << std::setprecision(2)
one last hint: The needed include files will be
#include <iostream>
#include <iomanip>
last you will need a loop have a look for for-loops or do-while loops.
This should help you to get your homework a good start.

am i on the right track? Cashier Program C++

I'm new to C++ and was wondering if i was on the right track? I'm kind of confused about this but was hoping for possibly some helpful hints on things i am missing/ have wrong....i know its not completely finished i still need to do the breakdown of the dollars,quarters....etc
Question: A cash register uses an automated coin machine to help make change. We assume that a clerk is handed money to pay for purchases. For change, the clerk returns to the customer any paper money and directs the coin machine to distribute any changes less then $1. In this exercise, you are to simulate the action of the clerk and the machine.
At the cash register, we need access to the purchase price and the payment. The change, which is the difference between the payment and the purchase prices, is a real number. The whole part represents the change in dollars and the fractional part is the change in cents that is returned in quarters, dimes, nickels, and pennies. For instance, with a payment of $10 to cover purchases of $3.08, the required change is $6.92. The clerk hand out $6 and the coin machine distributes 3 quarters, 1 dime, 1 nickel, and 2 pennies for the 92 cents.
92 = 3(25) + 1(10) + 1(5) + 2
Use real-number objects that identify the purchase price (price), the amount of payment (payment), and the change (change). The main program computes the amount of change (coinChange) and partitions it into dollars (dollars), quarters (quarters), dimes (dimes), nickels (nickels), and pennies (pennies).
You must declare constants for quarters (quarters), dimes (dimes), nickels (nickels), and pennies (pennies). You must use compound operators in the calculations. You must use setreal(w,p) and setw(n) for the output.
What I have done so far:
// Me
// A BRIEF PROGRAM DESCRIPTION FOR CHAPTER 2, HOMEWORK 4
// COMMENT THE PREPROCESSOR
#include <iostream.h>
// COMMENT THE PREPROCESSOR STATEMENT
#include "textlib.h"
int main( )
{
// COMMENT THE CONSTANTS
const int QUARTER_AMOUNT = 25;
const int DIME_AMOUNT = 10;
// COMMENT THE OBJECTS
double price;
double payment;
double change;
int numofDollars;
int numofQuarters;
int numofDimes;
int numofNickles;
int numofPennies;
int coinChange;
cout << "Enter the purchase total: ";
cin >> price;
cout << "Enter the payment: $";
cin >> payment;
// COMMENT THE CALCULATION
change = payment - price;
numofDollars = int(change);
coinChange = (int((change / numofDollars) * 100));
numofQuarters = coinChange / 25;
coinChange = coinChange / (numofQuarters * 25);
numofDimes = coinChange / 10;
numofNickles = coinChange / 5;
numofPennies = coinChange / 1;
// OUTPUT THE INFORMATION
return 0;
}
Yes, you are on the right track. Your general structure is sound. These sorts of homework assignments almost always have a structure like this:
int main () {
// read in the data
...
// Do the math
...
// Write out the data
...
}
You do have some math errors. Try stepping through the code with a pencil and paper, pretending that you are the computer. Also, try stepping through the code with your debugger, examining the variables after each line. Compare what actually happened to what you expected.