For Loops for a Time Class - c++

I am trying to write a for loop for a time class. Where if the minutes entered are over 60, 60 is subtracted from the total minutes and hours is incremented by 1 until the final minutes left is less than 60 . I was doing if statements like
if (m > 59){
m = m - 60;
h++;
if (m > 59)... etc..
but that doesn't cover every case and I feel like I should know how to do this for loop but I can't figure it out. Any help would be appreciated, thanks

Well if it doesn't have to be implemented using loops, you could do simply
h = m / 60;
m = m % 60;
It is the fastest and cleanest way to do that, I suppose.
Not really sure whether you want to do anything else inside the loops. If so, this won't help you very much.
Edit:
Here is some explanation of how it works.
What m / 60 does is called integer division. It returns floor of the expression. So for example if m = 131 than m / 60 = 2.
The second expression uses the modulo operator. Basically it finds the reminder after division. Back to our example, m % 60 = 11 since m can be written as m = 60 * 2 + 11 = 131. For further information please refer to wiki.

#Jendas has a good simple answer to the overall problem, but if you want to keep with this format but fix your issue with loops, you could put the whole thing in a while loop instead of individual if statements:
while(m >59)
{
m = m - 60;
h++;
// do anything else you need to take care of
}
// finishing statements

h = 0;
while (m >= 60)
{
m = m - 60;
h++;
}
You probably want to use >= 60 instead of 59.
Also, as Jendas rightly suggested you might want to research a little about the modulus operator '%'

Related

What am I misunderstanding when determining if a value is between two numbers?

I have a PDF form that adds up several different answers and displays the sum of these answer at the bottom of the page. I want to take that number, and have a sentence underneath it display three different options depending on the sum.
Greater than 60: Proceed
between 45 & 60: Consult Sales Lead
Less than 45: Decline
I am attempting to run a custom calculation script that takes the sum (which is named "total") and writes the above options, but I'm running into a myriad of errors.
My code I've written is below
var A = this.getField("total").value;
if (A >= 60){
event.value = "Proceed";
} else {
if (A <= 45){
event.value = "Decline";}
} else {
if (A < 60 && A > 45){
event.value = "Proceed, decision made with sales leader";}
}
If I were to only write the below block, I do not get any errors.
var A = this.getField("total").value;
if (A >= 60){
event.value = "Proceed";
}
I'm a newbie when it comes to most JavaScript, so any help is greatly appreciated! Thanks in advance!
I have based most of my code off of different search results from google. My main source
example 1
Below are a few other links I've referenced
example 2
example 3
You can leave away the
if (A < 60 && A > 45) {
line, because that condition is always true after the two previous conditions.
And then, it should work properly.
Just if you want to stay with that last condition, you would have to close it with a curly brace.
I think I managed to figure it out! For some reason, the addition of the "else" factor was causing syntax errors, so I tried it without and it seems to work as intended!
My code, for anyone that happens to find this, is the following:
var A = this.getField("total").value;
if (A >= 60) {event.value = "Proceed";}
if (A <= 59 && A >= 46) {event.value = "Proceed, decision made with sales leader";}
if (A <= 45) {event.value = "Decline";}
if (A == 0) {event.value = " ";}
Thanks to everyone that took a look at this, even if you didn't get to comment before I figured it out!

Frustrating Math Problem, results not as expected (EDQ)

Here is my code, throttle comes out to -18 when I run the program, and when I do the math I get 77.941... which is what I'm looking for. I know this is an EDQ "Extremely Dumb Question", and I am most likely to experience a FIF, "Fist In Forehead" moment any minute but I am stuck on it for now. FYI, programming it on an Atmega 328P using Arduino IDE on Windows 10.
Following example prints -18 and according to my calcualtions it should be 77.941...
int throttle = (((800 - 270) * 100) / 680);
Serial.println(throttle);
This is the visualized code...
throttle = (((throttleSensor - oldMinValue) * (newMax - newMin)) / (oldMax - oldMin));
I am trying to do this, Convert a number range to another range, maintaining ratio
Also, I should add, it works fine when the result is below 47, above that it flips to a negative number.
The short answer is, (800 - 270) * 100 = 53000. which is too large a number for the space that was allocated for the calculation results, integer overflow.
so changing the code from this...
int throttle = (((800 - 270) * 100) / 680);
to this...
long largeValue = 100;
int throttle = (((800 - 270) * largeValue) / 680);
fixes the problem. The number 100 or value of (newMax - newMin) has to be a "long" or the processor will miscalculate. Someone, please correct me on this if need be or post a better answer if you got one. Also if someone has a better suggestion for the title so it can be easier found for future people with the same problem, go ahead and commend it below.
Thanks to the StackOverflow community for helping me solve this issue!
as #edgar_wideman answer suggest your sub result (53000) does not fit into 16bit integer <-32768,+32767>. You can avoid long use by bitshifting (dividing by power of 2) like this:
int sh=1; // shift stuff so it fits 16 bit
int throttle = (((800 - 270) * (100>>sh)) / (680>>sh));
This might not be exactly what you are looking for, but there is a function for changing values from one range to an other.
int y = map(value, minOld, maxOld, minNew, maxNew);
for example:
int y = map(10, 0, 50, 0, 100); // y would be 20

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.

One simple 'if' statement in Julia increases the run-time of my prime sieve by a factor of 15 – why?

I've been experimenting with various prime sieves in Julia with a view to finding the fastest. This is my simplest, if not my fastest, and it runs in around 5-6 ms on my 1.80 GHz processor for n = 1 million. However, when I add a simple 'if' statement to take care of the cases where n <= 1 or s (the start number) > n, the run-time increases by a factor of 15 to around 80-90 ms.
using BenchmarkTools
function get_primes_1(n::Int64, s::Int64=2)::Vector{Int64}
#=if n <= 1 || s > n
return []
end=#
sieve = fill(true, n)
for i = 3:2:isqrt(n) + 1
if sieve[i]
for j = i ^ 2:i:n
sieve[j]= false
end
end
end
pl = [i for i in s - s % 2 + 1:2:n if sieve[i]]
return s == 2 ? unshift!(pl, 2) : pl
end
#btime get_primes_1(1_000_000)
Output with the 'if' statement commented out, as above, is:
5.752 ms (25 allocations: 2.95 MiB)
Output with the 'if' statement included is:
86.496 ms (2121646 allocations: 35.55 MiB)
I'm probably embarrassingly ignorant or being terminally stupid, but if someone could point out what I'm doing wrong it would be very much appreciated.
The problem of this function is with Julia compiler having problems with type inference when closures appear in your function. In this case the closure is a comprehension and the problem is that if statement makes sieve to be only conditionally defined.
You can see this by moving sieve up:
function get_primes_1(n::Int64, s::Int64=2)::Vector{Int64}
sieve = fill(true, n)
if n <= 1 || s > n
return Int[]
end
for i = 3:2:isqrt(n) + 1
if sieve[i]
for j = i ^ 2:i:n
sieve[j]= false
end
end
end
pl = [i for i in s - s % 2 + 1:2:n if sieve[i]]
return s == 2 ? unshift!(pl, 2) : pl
end
However, this makes sieve to be created also when n<1 which you want to avoid I guess :).
You can solve this problem by wrapping sieve in let block like this:
function get_primes_1(n::Int64, s::Int64=2)::Vector{Int64}
if n <= 1 || s > n
return Int[]
end
sieve = fill(true, n)
for i = 3:2:isqrt(n) + 1
if sieve[i]
for j = i ^ 2:i:n
sieve[j]= false
end
end
end
let sieve = sieve
pl = [i for i in s - s % 2 + 1:2:n if sieve[i]]
return s == 2 ? unshift!(pl, 2) : pl
end
end
or avoiding an inner closure for example like this:
function get_primes_1(n::Int64, s::Int64=2)::Vector{Int64}
if n <= 1 || s > n
return Int[]
end
sieve = fill(true, n)
for i = 3:2:isqrt(n) + 1
if sieve[i]
for j = i ^ 2:i:n
sieve[j]= false
end
end
end
pl = Int[]
for i in s - s %2 +1:2:n
sieve[i] && push!(pl, i)
end
s == 2 ? unshift!(pl, 2) : pl
end
Now you might ask how can you detect such problems and make sure that some solution solves them? The answer is to use #code_warntype on a function. In your original function you will notice that sieve is Core.Box which is an indication of the problem.
See https://github.com/JuliaLang/julia/issues/15276 for details. In general this is in my perception the most important issue with performance of Julia code which is easy to miss. Hopefully in the future the compiler will be smarter with this.
Edit: My suggestion actually doesn't seem to help. I missed your output annotation, so the return type appears to be correctly inferred after all. I am stumped, for the moment.
Original answer:
The problem isn't that there is an if statement, but that you introduce a type instability inside that if statement. You can read about type instabilities in the performance section of the Julia manual here.
An empty array defined like this: [], has a different type than a vector of integers:
> typeof([1,2,3])
Array{Int64,1}
> typeof([])
Array{Any,1}
The compiler cannot predict what the output type of the function will be, and therefore produces defensive, slow code.
Try to change
return []
to
return Int[]

How do I go about getting the real result for 50%60 in C++

I please check this problem I'm creating a Time Base app but I'm having problem getting to work around the modulus oper (%) I want the remainder of 50%60 which I'm expecting to output 10 but it just give me the Lhvalues instead i.e 50. How do I go about it.
Here is a part review of the code.
void setM(int m){
if ((m+min)>59){
hour+=((min+m)/60);
min=0;
min=(min+m)%60;
}
else min+=m;
}
In the code m is passed in as 50 and min is passed in as 10
How do I get the output to be 10 for min in this equation min=(min+m)%60; without reversing the equation i.e
60%(min+m)
in C++ expression a % b returns remainder of division of a by b (if they are positive. For negative numbers sign of result is implementation defined).
you should do : 60 % 50 if you want to divide by 50
Or, if you want to get mins, i think you don't need to make min=0.
When you do 50 % 60, you get a remiainder of 50 since 50 cannot be divided by 60.
To get around this error, you can try doing do something like 70 % 60 to get the correct value as a result, since you do not want to use 60 % 50
This would follow the following logic:
Find the difference between 60 and min + m after min is set to zero if min + mis less than 60. Store it in a variable var initially set to zero.
check if the result is negative; if it is, then set it to positive by multiplying it by -1
When you do the operation, do min = ((min + m) + var) % 60; instead.
***Note: As I am unfamiliar with a Time Base App and what its purpose is, this solution may or may not be required, hence please inform me in the comments before downvoting if I there is anything wrong with my answer. Thanks!
It looks like you are trying to convert an integral number of minutes to an hour/minute pair. That would look more like this instead:
void setM(int m)
{
hour = m / 60;
min = m % 60;
}
If you are trying to add an integral number of minutes to an existing hour/minute pair, it would look more like this:
void addM(int m)
{
int value = (hour * 60) + min;
value += m;
hour = value / 60;
min = value % 60;
}
Or
void addM(int m)
{
setM(((hour * 60) + min) + m);
}