C modulos and Remainders - c

Hey, I'm having the toughest time figuring out how to display this result. Say for example I enter a number such as 59. Based off that number, I get a remaining result of 1 week(s) 2 Day(s) and 5 Hour(s). This is of course assuming one week has 40 hours and 1 day has 7 hours in order to get that output. Any help in the right direction would be helpful. So far I've set it up like so:
scanf("%d %d %d", &totalWeeksWorked, &totalDaysWorked, &totalHoursWorked);

This is not the fastest way, but is perhaps the most illustrative:
int numodweeks = input/(7*24);
int numofdays =input/24;
int numofhours = 24 - (input/24);
Using modulo:
int numofweeks = input/(7*24);
int numofdays = (input%numofweeks)/7;
int numofhours = (input%(numofdays*24));
Then display them how you want.

#include <stdio.h>
int const HOURS_PER_WEEK = 40;
int const HOURS_PER_DAY = 7;
int main() {
int total_hours = 59; // this is the input you get
int remaining = total_hours; // 'remaining' is scratch space
int weeks = remaining / HOURS_PER_WEEK;
remaining %= HOURS_PER_WEEK;
int days = remaining / HOURS_PER_DAY;
remaining %= HOURS_PER_DAY;
int hours = remaining;
printf("%d hours = %d weeks, %d days, %d hours\n",
total_hours, weeks, days, hours);
return 0;
}

Related

something's wrong with my algorithm that I can't figure out in a while loop in C. Solving a problem in cs50 credit: Luhn's algorithm

Update: I already figured out what's wrong, it's the function of adding the digits together. Some also pointed out how some parts of this code is unnecessary so I deleted it and it definitely helped! I was able to point out the problem more easily. Thank you guyss, appreciate it
I'm trying to figure out what I did wrong in the first step of the credit problem in CS50. Im trying to create a program that implements the Luhn algorithm. I already figured out how to add every other digit starting from the least significant one. But I have a problem in the part of multiplying every other digit by 2, and adding the digits of the products together individually. I first decided to do an array but I tried to do now a while loop since someone suggested it can be solved thru a loop. When I type in the credit number 4003600000000014, it returns the value of 24 instead of 13. I cant figure out the logical error, and ive already tried to solve it for hours. Would definitely appreciate your help!
#include <stdio.h>
#include <cs50.h>
int sum_digits(int number2);
int get_number_digits(long x);
int times_two(int x);
int main(void) {
//Prompt for input
long number = get_long("Card Number: \n");
//initialize number to two different variables for [1. multiplying by
//2, adding the products]
//[2. adding every other digit]
long number2 = number;
long number3 = number;
//Calculate checksum
//Multiply digits by 2 alternately starting from the tens place, then
//add the digit of the products NOTE: edit loop, something is wrong
long remainderr2, currentnumber2, product, initialsum;
currentnumber2 = number3 / 10;
number3 = currentnumber2;
int finalsum = 0;
while (currentnumber2 > 0)
{
number3 = currentnumber2;
remainderr2 = currentnumber2 % 10;
product = times_two(remainderr2);
initialsum = sum_digits(product);
finalsum = finalsum + initialsum;
currentnumber2 = currentnumber2 / 10;
currentnumber2 = currentnumber2 / 10;
}
printf("%ld", finalfinalsum);
}
//Function that adds the digits of a number
int sum_digits(int number2) {
int secondstep, remainderr, currentnumber, sum;
currentnumber = number2;
secondstep = 0;
while (number2 > 0) {
number2 = currentnumber;
sum = 0 + secondstep;
remainderr = currentnumber % 10;
secondstep = sum + remainderr;
currentnumber = number2 / 10;
}
return sum;
}
//Function that multiplies int by 2
int times_two(int x) {
x = x * 2;
return x;
}

how can i optimise this code so that it takes lesser run time?

The original question is:
A man has a rather old car being worth $2000.
He saw a secondhand car being worth $8000. He wants to keep his old
car until he can buy the secondhand one.
He thinks he can save $1000 each month but the prices of his old car
and of the new one decrease of 1.5 percent per month. Furthermore the
percent of loss increases by a fixed 0.5 percent at the end of every
two months.
Can you help him? Our man finds it difficult to make all these
calculations.
How many months will it take him to save up enough money to buy the
car he wants, and how much money will he have left over?
I have implemented this so far how can I improve this code.
int main (){
double percent=0.985; // the value by which the price of an item //reduces
int startPriceOld=2000; //price of an item i want to sell
int startPriceNew=8000;// price of an item i want to buy
int savingperMonth=1000; // my monthly savings
int init=0;
int mon=0; //no of months
int saving=0;
int diff=(saving*mon)-((pow(percent,mon))*(startPriceNew-startPriceOld));
/*checking the condition when the money I have by selling my old item in addition to my savings will be greater than the money I need to buy my new item*/
while(1)
{
mon++;
startPriceOld=percent*startPriceOld;
startPriceNew=percent*startPriceNew;
saving=init+mon*savingperMonth;
if(diff>0)
{break;}
}
int arr[2];
arr[0]=mon;
arr[1]=diff;
printf("%d",mon);
}
You can solve this with just math:
Price of the new car at each month:
(new_car_cost)*(1-(0.015+0.005*floor(month/2)))^month
Price of the old car at each month:
(old_car_cost)*(1-(0.015+0.005*floor(month/2))^month
Your salary:
1000*month
At the nth-month you will have:
new_car_cost = old_car_cost+salary
round up the month and you have solved the problem
You can also semplify the equation.
Tried solving your issue and reached to this solution:
#include <stdio.h>
int main (){
float priceOld=2000; //price of an item i want to sell
float priceNew=8000;// price of an item i want to buy
int savingperMonth=1000; // my monthly savings
int finalMonths = 0;
float finalLeft = 0;
int mon=0; //no of months
for (mon = 1; mon<9;mon++){
priceOld = priceOld - ((priceOld*15)/100);
priceNew = priceNew - ((priceNew*15)/100);
if( mon % 2 == 0 ){
priceOld = priceOld - ((priceOld*5)/100);
priceNew = priceNew - ((priceNew*5)/100);
}
if((priceOld + (savingperMonth*mon)) >= priceNew){
finalMonths = mon;
finalLeft = (priceOld + (savingperMonth*mon)) - priceNew;
printf("Number of months: %d\n", finalMonths);
printf("Final amount left: %f$", finalLeft);
break;
}
}
return 0;
}
I think This will work fine for you.!
Output in main loop is for understanding what's happening there :)
#include <stdio.h>
#include <stdlib.h>
int main ( )
{
/* will store it in cents */
unsigned int money_now = 0;
unsigned int salary = 100000;
unsigned int money_left;
unsigned int old_car_cost = 200000;
unsigned int new_car_cost = 800000;
float decr_percent = 0.015;
float decr_percent_diff = 0.005;
size_t months = 0;
while ( 1 )
{
months++; /* Month has passed */
money_now += salary; /* got salary*/
old_car_cost -= old_car_cost * decr_percent; /* new cost of old car */
new_car_cost -= new_car_cost * decr_percent; /* new cost of new car */
/*
meanings:
b - bugdet;
p - percent;
oc - old car cost;
nc - new car cost.
*/
printf("b:$%u;\tp:%.1f;\toc:$%u.%u;\tnc:$%u.%u\n",
money_now / 100, decr_percent * 100, old_car_cost / 100, old_car_cost % 100, new_car_cost / 100, new_car_cost % 100 );
/* if ( ours money + old car's cost ) is enough for new car */
if ( new_car_cost <= ( money_now + old_car_cost) ) break;
/*if it's end of every second month */
if ( 0 == (months % 2) ) decr_percent += decr_percent_diff;
}
puts(""); /* newline */
printf("It has been %lu months.\n", months );
money_left = ( money_now + old_car_cost ) - new_car_cost;
printf("Money left : $%u.%u\n", money_left / 100, money_left % 100);
return 0;
}

How to add two 24hour times

Hi pretty new to coding in c, but would love your help in my following coding problem.
I want to add two times (that are in twenty four hour time notation already).
Currently they are both integers and the arithmatic addition function is great for whole hour (e.g. 800+1000), however because our / computer's numbers are base ten, it will not roll over to the next hour after 60min which leads to problems with addition.
I'm not sure if the modulus % can solve this? Ideally I would like to use simple c coding (that I understand), and not start importing timing keys into the program.
e.g.
#include <stdio.h>
int main (void)
{
int time1 = 1045; // 10:45am in 24hour time
printf("Time %d ",time1);
int time2 = 930; //9 hours & 30min
printf("+ time %d", time2);
int calc = time1 + time2;
printf(" should not equal ... %d\n", calc);
printf("\nInstead they should add to %d\n\n", 2015); //8:15pm in 24hr time
return 0;
}
Yes, you're correct that modulo division is involved. Remember, that is remainder division. This is more worthy as a comment since supplying a complete answer for problems like this is generally frowned upon, but it's too long for that; this should get you started:
#include <stdio.h>
int main(void)
{
// Assuming the given time has the format hhmm or hmm.
// This program would be much more useful if these were
// gathered as command line arguments
int time1 = 1045;
int time2 = 930;
// integer division by 100 gives you the hours based on the
// assumption that the 1's and 10's place will always be
// the minutes
int time1Hours = time1 / 100; // time1Hours == 10
int time2Hours = time2 / 100; // time2Hours == 9
// modulus division by 100 gives the remainder of integer division,
// which in this case gives us the minutes
int time1Min = time1 % 100; // time1Min == 45
int time2Min = time2 % 100; // time2Min == 30
// now, add them up
int totalHours = time1Hours + time2Hours; // totalHours = 19
int totalMin = time1Min + time2Min; // totalMin = 75
// The rest is omitted for you to finish
// If our total minutes exceed 60 (in this case they do), we
// need to adjust both the total hours and the total minutes
// Clearly, there is 1 hour and 15 min in 75 min. How can you
// pull 1 hour and 15 min from 75 min using integer and modulo
// (remainder) division, given there are 60 min in an hour?
// this problem could be taken further by adding days, weeks,
// years (leap years become more complicated), centuries, etc.
return 0;
}
I used this for a long time...
// convert both times hhmm to minutes an sum minutes
// be sure to do integer division
int time1m = ((time1 / 100) * 60)+(time1 % 100);
int time2m = ((time2 / 100) * 60)+(time2 % 100);
int sumMin = time1m + time2m;
// convert back to hhmm
int hhmm = ((sumMin / 60) * 100)+(sumMin % 60);
You can also include a day, as time is of 24 hour format.
#include <stdio.h>
int main()
{
int t1=2330;
int t2=2340;
int sum=((t1/100)*60)+(t1%100)+((t2/100)*60)+(t2%100);
int day=sum/(24*60);
sum = sum % (24*60);
int hours=sum/(60);
int mins=sum % 60;
printf("days = %d \t hours = %d \t mins=%d\n",day, hours, mins);
return 0;
}

Why is there a computation error when returning function with structure

I am trying to find the number of elapsed days between two dates. However, with some dates the program prints the wrong number of days between 2 dates.
The formula for number of elapsed days is: N=1461 x f(year,month) / 4+ 153 x g(month)/5 +day
In my program, I have f and g defined as functions that return different values of years and months depending on what the user inputs.
The main problem probably lies with how I scanned the user input with the local variables in the date structure.
N1 is the number of elapsed days for the 1st date. N2 is for the second date.
Below is my written code:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
struct date {
int month;
int day;
int year;
};
int f( int theyear, int themonth){
if (themonth <=2)
theyear = theyear-1;
else
theyear =theyear;
return theyear;
}
int g( int Month){
if (Month<=2)
Month=Month+13;
else
Month = Month+1;
return Month;
}
int main()
{
struct date time1, time2;
int N1; int N2;
printf("Enter time1 (mm,dd,yyyy): ");
scanf("%i%i%i", &time1.month, &time1.day, &time1.year);
printf("Enter time2 (mm,dd,yyyy): ");
scanf("%i%i%i", &time2.month, &time2.day, &time2.year);
N1=1461 * f(time1.year,time1.month) / 4 + 153 * g(time2.month) / 5 +3;
N2 = 1461 * f(time2.year,time2.month)/4 +153 * g(time2.month)/5 +21;
printf("%d \n",abs(N1 -N2));
return 0;
}
Thank you very much. :)
Sample input/output:
Enter time1 (mm,dd,yyyy): 04 10 1994
Enter time2 (mm,dd,yyyy): 03 10 1994
18
As you can see, it prints out 18. However, it is supposed to be the number of days in a month.
change
N1=1461 * f(time1.year,time1.month) / 4 + 153 * g(time2.month) / 5 +3;
N2 =1461 * f(time2.year,time2.month)/4 +153 * g(time2.month)/5 +21;
to
N1=1461 * f(time1.year,time1.month) / 4 + 153 * g(time1.month) / 5 + time1.day;
N2 =1461 * f(time2.year,time2.month)/4 +153 * g(time2.month)/5 + time2.day;
?

compounding / while loops

#include <stdio.h>
int main(void)
{
int days, hours, mins;
float a, b, c, total, temp, tempA, tempB;
a = 3.56;
b = 12.50;
c = 9.23;
total = a+b+c;
days = total / 24;
temp = total/24 - days;
hours = temp * 24;
tempA = temp*24 - hours;
mins = tempA*60;
while (hours >= 24)
{
hours= hours-24;
days +=1;
}
while ( mins >= 60)
{
mins=mins-60;
hours +=1;
}
printf("days:%d\n", days);
printf("hours:%d\n", hours);
printf("mins:%d\n", mins);
return 0;
}
I wanted to convert decimal hours to real time and I can do it fine but I wanted to increase days hours if the hours is beyond 24 and if mins is beyond 60mins.
the while loop does subtract and it does print out the new value but the hours / days aren't getting compounded.
It was 1 day 1 hour 77mins
I wanted it to read 1 day 2 hours 17mins
but I'm getting 1 day 1 hour 17 mins.
Using the modulus operator will make your life much easier: it will give the remainder of a division.
int total;
/* a=; b=; c=; assignments */
total = a+b+c;
mins = total % 60;
total /= 60;
hours = total % 24;
days = total / 24;
Here is a simpler implementation of what you are trying to do:
void TimeFix(int &days, int &hours, int &mins)
{
hours += mins/60;
mins %= 60;
days += hours/24;
hours %= 24;
}
Running your program I'm getting:
days:1
hours:1
mins:17
and that's what I expect considering that total should be 25.29.
It works fine, your math is just a little off. (= (+ 3.56 12.50 9.23) 25.29), not 26.29.
Instead of a while loop you can use division:
days += hours / 24
hours %= 24
Also, do your minutes-to-hours stuff before your hours-to-days stuff.

Resources