How do you use the "%" operator in C++? - c++

I have to take a number of days and convert them into weeks and days.
I know I have to use the % operator, but how do I use it?

% is the modulo (remainder) operator. In your case, try:
int weeks = total_days / 7;
int remaining_days = total_days % 7;

Odd how when people asking a question say "I know", they're often wrong. You don't need modulus (%) at all.
int weeks = total_days / 7;
printf("%d days is equal to %d weeks and %d days.\n",
total_days, weeks, total_days - weeks*7);

Actually you can divide the total number of days by 7 and you will get the weeks.
THen you can perform modulo on total number of days with 7 and you get the days remaining.
Is this not enough

% (modulus operator) gives you the remainder. So days % 7 will give you the amount of days left after converting to weeks. i.e. if days = 15, then days % 7 would equal 1.

Related

Best way to find difference between two values in a cyclic system?

Take for example time: if we have the starting hour and ending hour, what's the best way to find the number of hours between them?
If we take a 12-hour clock, we'd get the following results
from 1 to 5 = 4
from 11 to 1 = 2
What is the most efficient way to do that?
Assuming a 12 hour clock, the number of hours from a to b can be calculated as:
difference = ((b + 12) - a) % 12;
This also assumes that a and b are both in the range [1, 12]. In case they are not, you can do:
a %= 12;
b %= 12;
before doing the difference calculation.
Assuming input already in range 1-12, you might do
return b - a + (b < a) * 12;
benchmark showing a 2 times performance gain over cigien's solution.

How to round numbers in range after division (10.25 to 11)? [duplicate]

This question already has answers here:
Rounding up and down a number C++
(5 answers)
Closed 4 years ago.
For a school project I need to calculate the leap years. The problem is, I need to round the int.
For example someone is born in 1961.
double yearsbetween; yearsbetween = birthyear - 1918;
double leapyears; leapyears = ( yearsbetween / 4 );
If birthyear = 1961 I get leapyears = 10.75 but that is wrong.. I need to be 11.
If an answer is 10.25 it need to be rounded to 10. If an answer is 10.75 it need to be rounded to 11.
Can someone help me ?
you have to specifically look at each year to check for leap years. your assumption of every 4th year as leap is wrong, as there are some exceptions:
it is not a leap year, if it is divisible by 100 and not divisible by 400
examples:
1900 is not a leap year
2000 is a leap year
see https://en.wikipedia.org/wiki/Leap_year#Algorithm
Suppose we are working only in a period in which the leap years are those years, and only those years, that are divisible by four.
Given a number n, the number of positive numbers less than or equal to n that are multiples of four is floor(n/4). Let L(n) be this value, floor(n/4).
If we take a number m, the number of positive multiples of four up to m is L(m). When we subtract L(n), the result, L(m)−L(n), is the number of multiples of four greater than n but less than or equal to m.
Therefore, the number of leap years between year 1918 and year m is floor(m/4) − floor(1918/4) = floor(m/4) − 479. (If the base year were a leap year and we wanted to include it inside the period instead of outside, we could replace L(n) with L(n−1).
The above is easily extendable to the larger leap year pattern. By changing L(n) to floor(n/4) − floor(n/100) + floor(n/400), it becomes a count of positive numbers up to n that are multiples of four but are not multiples of 100 unless they are multiples of 400. Then L(m) − L(n) is the number of leap rules between n and m.
Thus a proper formula for the period covered by this rule is floor(n/4) − floor(n/100) + floor(n/400) − 464. Using C’s integer arithmetic, this is easily evaluated as n/4 - n/100 + n/400 - 464.
Seems like what you need is std::ceil
You also have in the std::ceil reference a link to other rounding functions, I recommend
going through those also.
So this isn't relevant until c++20 and I even had to ask a question to figure out how to use chrono::year. But the best solution for this, if available, would be something like:
const chrono::year birthyear{ 1961 };
auto leapyears = 0;
for(chrono::year i{ 1918 }; i <= birthyear; ++i) {
if(i.is_leap()) {
++leapyears;
}
}
I've linked a live example by forking #HowardHinnant's example from this answer.

Not understanding mathematical solution to implementation task

The problem sounds like that:
Kevin has N friends and one building. He wants to organize a
party in that building and he invites exacly 1 friend / day. Kevin
unfortunately has grumpy neighbors which aren't too happy with the
noise that Kevin's party does. For that, Kevin wants to minimize the
noise level of his party. (the noise level is equal to the number of
friends in the building) In order to do that, after some day he can
clear the building by asking his friends to leave (he can do that K times, for K different days). (ex: he clears the
building after day 2 so at day 3 when he invites another friend, for
day 3 the noise level will be 1 because the past day he cleared the
building; if he didn't clear the building at day 2, the noise level
for day 3 will have been 3 (1 from day 2, 1 from day 1 and the new invited friend) and the total noise level for day 1, 2 and 3 would have been 1+2+3=6).
For better understanding the task:
Input:
5 2 (N, K)
Output:
7
Explanation:
In the input example, N friends will be invited at the party, in the following order:
1 (day 1) 1 (day 1)
1 (day 2) so in the building for each day will be present 2 (day 2)
1 (day 3) -------------------------------------------------> 3 (day 3)
1 (day 4) (without clearing the building) 4 (day 4)
1 (day 5) 5 (day 5)
-----(+)
15
So, clearing the building 0 times (K=0), the noise level will be 15.
Clearing the building 1 time (K=1), the sum will be:
(0 times)
1 1
__ 2 __ clearing the building after day 2 2
3 -----------------------------------> 1
4 2
5 3
----(+)
9
At this case (K=1), another solution could be to clear after day 3, same sum.
Clearing 2 times (K=2):
(0 times)
1 1
__ 2 __ clearing the building after day 2 & 3 2
__ 3 __ --------------------------------------> 1
4 1
5 2
----(+)
7
I have the solution but I don't understand it!
I tried, took some other cases but still nothing, maybe you guys can explain me why the solution is the way it is.
This is how sum(N, K) is calculated:
sum(N, K) = minimum noise level clearing the building K times (K>=0)
C++ code:
int sum(int n)
{
return n * (n + 1) / 2;
}
int solve(int n, int k)
{
int p = k + 1;
int mp = n/p;
int bp = (n+p-1)/p;
int nmaj = n%p;
int nmic = p-nmaj;
return nmic * sum(mp) + nmaj*sum(bp);
}
What is the purpose of each variable?
What does nmic * sum(mp) and nmaj*sum(bp) computes?
!!!!
For the example above (at the beginning - N=5, K=2), I debugged the code and wrote for N=5, K=0..2 the value for each variable, hoping to get the idea but no succes. I am going to post them for you, maybe you'll get the idea and then explain to me (I am a novice in algorithmic problems).
Here is it:
variable values for each case
I repeat, I tried for some hours to understand but no succes. And it's not a homework. Thank you!
The code goes like this:
int p = k+1;
p is the number of "parts" in which you divide the days (Ex: Day1 + Day2 = part1, Day 3 + Day4 = part2, Day 5 = part3)
int mp = n/p;
mp is the amount of days the minor part has, in the example is 1 (Day5). It's calculated as the floor of the number of days over the number of parts.
int bp = (n+p-1)/p;
bp is the amount of days in the bigger part, in the example is 2 (Day1 + Day2 or Day3 + Day4). I don't really get the exact math behind but that's what it calculates
int nmaj = n%p;
int nmic = p-nmaj;
nmaj is the number of major parts, in the example is 2 (Day1 + Day2 and Day3 + Day4), the nmic is the number of minor parts (1 for Day5).
nmic * sum(mp) + nmaj*sum(bp);
This just returns the number of minor parts * the accumulated value in minor parts + number of major parts * the accumulated value in major parts
The sum function is just the formula for arithmetic series (Or summation of arithmetic progressions) for the special case of initial element = 1

Find the difference between the dates and group it under some category

I have a start date and an end date. I need to find the difference between these dates and group it under the following categories.
< 1 year, < 2 year and so on till X years.
I'm trying to write a unix C++ program for this problem.
I can easily find the unix time difference between start and end date and compare with the 1 year's time stamp (12 * 30 * 20 * 60 * 60) and so on.
Is there any C++ function that returns the difference in years given the start and end date? Also let's say, the difference is 8 years, I suppose I have to write conditions like this,
if((end_date - start_date) < 12 * 30 * 24 * 60 * 60)
group = " less than 1 year"
...
...
Until what point do I stop at, as I won't know what the maximum difference is between the dates?
Is there any easy way to compute this?
I know i'm confusing here, but i ve put all my efforts to explain the problem here. Thanks in advance.
Also note, this is not a assignment or anything.
Assuming "precise years" (in other words, all years are 365 days long) is not an issue, I would do something like this (counting the number of times each year happens in this case - since the original question doesn't really say WHAT to do with each year)
const int MAX_YEARS = 10;
const int YEAR_IN_SECONDS = 365 * 24 * 60 * 60;
std::array<int, MAX_YEARS+1> bins;
int years = static_cast<int>(difftime(end_date - start_date) / YEAR_IN_SECONDS);
// Outside of range, put it at the end of range...
// We could discard or do something else in this case.
if (years > MAX_YEARS)
{
years = MAX_YEARS;
}
bins[years]++; // Seen one more of "this year".
Obviously, what you do with "bins", and what/how you store data there really depends on what you actually are trying to achieve.
An alternative solution would be to use const double YEAR_IN_SECONDS = 365.25 * 24 * 60 * 60;, which would slightly better cover for leap-years. If you want to be precise about it, you'd have to find out if you are before or after each of the leapday in a particular year that is divisible by 4 (and keep in mind that there are special cases for years divisible by 100 and other rules at 400).
#include <chrono>
using years = std::chrono::duration<std::chrono::system_clock::rep, std::ratio<365 * 24 * 60 * 60, 1>>;
std::chrono::system_clock::time_point end_date = std::chrono::system_clock::now();
std::chrono::system_clock::time_point start_date = end_date - years(2);
years how_many = std::chrono::duration_cast<years>(end_date - start_date);
int how_many_as_int = how_many.count();
std::cout << how_many_as_int << std::endl;
std::unordered_map<int, std::list<whatever>> m;
m[how_many_as_int].push_back(...);

How to improve my code about the growing of a bacterial colony (C++) [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I'm coding a program to calculate the growth of a bacterial colony until certain point.
Given a "X", that will represent the initial number of bacteria. And given a "Y", that will represent the number limit desired of bacteria in the bacterial colony. Return the number of days and hours that the bacterial colony needs for reaching the limit.
The bacterial colony doubles each hour.
Example.1:
Input: 1, 8
Output: 0, 3
Example.2:
Input: 1000 , 1024000
Output:0, 10
Example.3:
Input: 123, 3453546624536
Output: 1, 10
If the hour calculated returns a fractional number, it must be rounded down.
So far I have written this code:
#include <iostream>
using namespace std;
int main(){
long int binitial, blimit, day, counter=0;
float hour;
cin >> binitial;
cin >> blimit;
while(binitial <= blimit){
binitial = binitial * 2;
counter++;
}
day = counter / 24;
cout << day << " ";
hour = (counter % 24) - 0.5;
cout << (int)hour;
return 0;
}
You can remove the loop by observing that the number of hours is Log2(Y/X). To calculate Log2(A) using the standard functions, calculate log(A)/log(2).
You may need to address precision issues when going from doubles to ints, because the calculations will be approximate. The final expression for the hours may look like this:
int hours = (log(Y/X) / log(2)) + 1E-8; // Add a small delta
Going from hours to days/hours is very simple, too:
cout << hours/24 << " " << hours % 24 << endl;
You can use a long int for hour if you do the following:
hour = counter - (day*24); // The total number of hours minus the number of hours that are in each day.
I don't have a compiler in front of me but you can probably also do something like this:
hour = counter % 24; // this will return the remainder when counter is divided by 24.
If blimit is always a multiple of binitial, the solution is simple:
counter%24 will be always an integer, so you don't have to round it.
In case of day days and hour hours, you only have to do is:
hour = counter%24
A note on the method of calculation: you don't need to iterate if you're only doubling each time. You're just looking for a value of n such that 2n gives the right result.
So, note that ngenerations = log2 blimit - log2 binitial
Once you have the number of generations (as a floating-point number) you can just truncate that to an integer number of hours.