This program is supposed to store time in seconds since midnight and display it in standard and universal time. It runs, but the set Time function has an error in it, as the time never changes. I'm assuming that something isn't being returned right, but I can't find the error.
Header file :
#ifndef TIME_H
#define TIME_H
class Time
{
public:
Time(); //constructor
void setTime(int, int, int );
void printUniversal(); //print time in universal-time format
void printStandard(); // print time in standard-time format
private:
int secondsSinceMidnight;
};
#endif
.cpp file
Time::Time()//constructor
{
secondsSinceMidnight = 0;
}
void Time::setTime(int h, int m, int s)
{
if ((h >= 0 && h < 24) && (m >= 0 && m < 60) && (s >= 0) && (s < 60))
{
int hoursInSecs = (h * 3600);
int minutesInSecs = (m * 60);
secondsSinceMidnight = (minutesInSecs + hoursInSecs);
}
else
throw invalid_argument(
"hour, minute and/or second was out of range");
}
void Time::printUniversal()
{
int secondsSinceMidnight = 0;
int hours = (secondsSinceMidnight / 3600);
int remainder = (secondsSinceMidnight % 3600);
int minutes = (remainder / 60);
int seconds = (remainder % 60);
cout <<setfill('0')<<setw(2)<<hours<<":"
<<setw(2)<<minutes<<":"<<setw(2)<<seconds<<endl;
}
void Time::printStandard()
{
int secondsSinceMidnight = 0;
int hours = (secondsSinceMidnight / 3600);
int remainder = (secondsSinceMidnight % 3600);
int minutes = (remainder / 60);
int seconds = (remainder % 60);
cout<<((hours == 0 || hours == 12) ? 12 : hours % 12) << ":"
<< setfill('0') <<setw(2)<<minutes<< ":"<<setw(2)
<<seconds<<(hours < 12 ? "AM" : "PM")<<"\n";
}
And the main program :
int main()
{
Time t; //instantiate object t of class Time
//output Time object t's initial values
cout<<"The initial universal time is ";
t.printUniversal();
cout<<"\nThe initial standard time is ";
t.printStandard();
int h;
int m;
int s;
cout<<"\nEnter the hours, minutes and seconds to reset the time: "<<endl;
cin>>h>>m>>s;
t.setTime(h, m, s); //change time
//output Time object t's new values
cout<<"\n\nUniversal time after setTime is ";
t.printUniversal();
cout<<"\nStandard time after setTime is ";
t.printStandard();
}
In your print functions you have a local variable with the same name as your field secondsSinceMidnight. It is shadowing it.
Why there are
int secondsSinceMidnight = 0; at the beginning of printUniversal() and printStandard(), this variable would cover member variable.
At the beginning of both of your print functions, you set secondsSinceMidnight = 0. Leave that in the constructor, but remove it from the print functions.
Related
So I was inspired by a recent Youtube video from the Numberphile Channel. This one to be exact. Cut to around the 5 minute mark for the exact question or example that I am referring to.
TLDR; A number is created with all the digits corresponding to 1 to N. Example: 1 to 10 is the number 12,345,678,910. Find out if this number is prime. According to the video, N has been checked up to 1,000,000.
From the code below, I have taken the liberty of starting this process at 1,000,000 and only going to 10,000,000. I'm hoping to increase this to a larger number later.
So my question or the assistance that I need is optimization for this problem. I'm sure each number will still take very long to check but even a minimal percentage of optimization would go a long way.
Edit 1: Optimize which division numbers are used. Ideally this divisionNumber would only be prime numbers.
Here is the code:
#include <iostream>
#include <chrono>
#include <ctime>
namespace
{
int myPow(int x, int p)
{
if (p == 0) return 1;
if (p == 1) return x;
if (p == 2) return x * x;
int tmp = myPow(x, p / 2);
if (p % 2 == 0) return tmp * tmp;
else return x * tmp * tmp;
}
int getNumDigits(unsigned int num)
{
int count = 0;
while (num != 0)
{
num /= 10;
++count;
}
return count;
}
unsigned int getDigit(unsigned int num, int position)
{
int digit = num % myPow(10, getNumDigits(num) - (position - 1));
return digit / myPow(10, getNumDigits(num) - position);
}
unsigned int getTotalDigits(int num)
{
unsigned int total = 0;
for (int i = 1; i <= num; i++)
total += getNumDigits(i);
return total;
}
// Returns the 'index'th digit of number created from 1 to num
int getIndexDigit(int num, int index)
{
if (index <= 9)
return index;
for (int i = 10; i <= num; i++)
{
if (getTotalDigits(i) >= index)
return getDigit(i, getNumDigits(i) - (getTotalDigits(i) - index));
}
}
// Can this be optimized?
int floorSqrt(int x)
{
if (x == 0 || x == 1)
return x;
int i = 1, result = 1;
while (result <= x)
{
i++;
result = i * i;
}
return i - 1;
}
void PrintTime(double num, int i)
{
constexpr double SECONDS_IN_HOUR = 3600;
constexpr double SECONDS_IN_MINUTE = 60;
double totalSeconds = num;
int hours = totalSeconds / SECONDS_IN_HOUR;
int minutes = (totalSeconds - (hours * SECONDS_IN_HOUR)) / SECONDS_IN_MINUTE;
int seconds = totalSeconds - (hours * SECONDS_IN_HOUR) - (minutes * SECONDS_IN_MINUTE);
std::cout << "Elapsed time for " << i << ": " << hours << "h, " << minutes << "m, " << seconds << "s\n";
}
}
int main()
{
constexpr unsigned int MAX_NUM_CHECK = 10000000;
for (int i = 1000000; i <= MAX_NUM_CHECK; i++)
{
auto start = std::chrono::system_clock::now();
int digitIndex = 1;
// Simplifying this to move to the next i in the loop early:
// if i % 2 then the last digit is a 0, 2, 4, 6, or 8 and is therefore divisible by 2
// if i % 5 then the last digit is 0 or 5 and is therefore divisible by 5
if (i % 2 == 0 || i % 5 == 0)
{
std::cout << i << " not prime" << '\n';
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
PrintTime(elapsed_seconds.count(), i);
continue;
}
bool isPrime = true;
int divisionNumber = 3;
int floorNum = floorSqrt(i);
while (divisionNumber <= floorNum && isPrime)
{
if (divisionNumber % 5 == 0)
{
divisionNumber += 2;
continue;
}
int number = 0;
int totalDigits = getTotalDigits(i);
// This section does the division necessary to iterate through each digit of the 1 to N number
// Example: Think of dividing 124 into 123456 on paper and how you would iterate through that process
while (digitIndex <= totalDigits)
{
number *= 10;
number += getIndexDigit(i, digitIndex);
number %= divisionNumber;
digitIndex++;
}
if (number == 0)
{
isPrime = false;
break;
}
divisionNumber += 2;
}
if (isPrime)
std::cout << "N = " << i << " is prime." << '\n';
else
std::cout << i << " not prime" << '\n';
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
PrintTime(elapsed_seconds.count(), i);
}
}
Its nice to see you are working on the same question I pondered few months ago.
Please refer to question posted in Math Stackexchange for better resources.
TL-DR,
The number you are looking for is called SmarandachePrime.
As per your code, it seems you are dividing with every number that is not a multiple of 2,5. To optimize you can actually check for n = 6k+1 ( 𝑘 ∈ ℕ ).
unfortunately, it is still not a better approach with respect to the number you are dealing with.
The better approach is to use primality test screening to find probable prime numbers in the sequence and then check whether they are prime or not. These tests take a less time ~(O(k log3n)) to check whether a number is prime or not, using mathematical fundamentals, compared to division.
there are several libraries that provide functions for primality check.
for python, you can use gmpy2 library, which uses Miller-Rabin Primality test to find probable primes.
I recommend you to further read about different Primality tests here.
I believe you are missing one very important check, and it's the division by 3:
A number can be divided by 3 is the sum of the numbers can be divided by 3, and your number consists of all numbers from 1 to N.
The sum of all numbers from 1 to N equals:
N * (N+1) / 2
This means that, if N or N+1 can be divided by 3, then your number cannot be prime.
So before you do anything, check MOD(N,3) and MOD(N+1,3). If either one of them equals zero, you can't have a prime number.
I have been trying to solve this problem for an online judge system, which requires a time limit of 1000ms. I have tried a few variations of solutions, but I will post my best draft here. I was able to get my answers right, however, I am exceeding the time limit. The best solution I can come up with is O(n^2).
The Task problem
Once the programmer X was in China and noticed that Russian clocks “Zarya” are 10 times cheaper there than in Russia. X chose to do some shenanigans and bought a huge amount of clocks to bring it to his own country and sell them at half price (which actually means 5x times more expensive than he bought). But as soon as he came back home, he realized that many clocks go discordantly, moreover, they stop from a simple push (or start going if they were stopped before).
Obviously, the clocks were fake, just very accurate copies. To sell them really quickly, X wants to set them all to the same time (so it won’t matter if the time’s correct or not – he can say this is “the time of the manufacturer”) and just shake his bag to make them tick.
To set the time, he has to spin a winding crown that will make clock’s hands move: the hour hand moves 60 times slower than the minute hand and the minute hand is 60 times slower than the second hand. One full spin of a crown makes a full spin of the second hand; and although the spin takes just a second, it will take 6 minutes to change the time to 6 hours. It is allowed to spin a crown only clockwise to save fragile mechanism of a clock.
Help the programmer X minimize the effort put in preparing the clocks to be sold, choosing the optimal time to set all clocks to.
Input:
The first line contains a natural n (1 ≤ n ≤ 50000) – the quantity of clocks.
The next n lines contain the time of each clock in a format “h:mm:ss”, where h (1 ≤ h ≤ 12) means hours, mm and ss (00 ≤ mm,ss ≤ 59) – minutes and seconds.
Output:
The time all clocks need to be set to in the format presented above.
Example Input
3
11:30:00
12:10:01
6:10:18
Output
12:10:01
#include<iostream>
using namespace std;
struct Clock {
int hours;
int mins;
int secs;
Clock() {
hours = mins = secs = 0;
}
};
void strtotime(string str, Clock& clock) { //converts string input to time
if (str[1] == ':') {
clock.hours = (str[0] - 48);
clock.mins = (str[2] - 48) * 10 + (str[3] - 48);
clock.secs = (str[5] - 48) * 10 + (str[6] - 48);
}
else {
clock.hours = (str[0] - 48) * 10 + (str[1] - 48);
clock.mins = (str[3] - 48) * 10 + (str[4] - 48);
clock.secs = (str[6] - 48) * 10 + (str[7] - 48);
}
}
double calctime(Clock from, Clock to) {//calculates time taken to change one clock time to other's
//calculate time for hours
double minutes;
if (from.hours > to.hours) {
minutes = 12 - (from.hours - to.hours);
}
else {
minutes = to.hours - from.hours;
}
//calculate time for mins
double seconds;
if (from.mins > to.mins) {
seconds = 60 - (from.mins - to.mins);
}
else {
seconds = to.mins - from.mins;
}
//calculate time for secs
double seconds2;
if (from.secs > to.secs) {
seconds2 = 60 - (from.secs - to.secs);
}
else {
seconds2 = to.secs - from.secs;
}
double totalTime = minutes * 60 + seconds + (seconds2 / 60);
return totalTime;
}
int main() {
int n;
string str;
cin >> n;
Clock* clock = new Clock[n];
for (int x = 0; x < n; x++) {
cin >> str;
strtotime(str, clock[x]);
}
double totaltime;
double mintime;
int loc = 0;
bool first = true;
double* timearr = new double[n];
for (int x = 0; x < n; x++) {
totaltime = 0.0;
for (int y = 0; y < n; y++) {
if (x != y) {
totaltime += calctime(clock[y], clock[x]);
}
}
if (first) {
mintime = totaltime;
first = false;
}
else {
if (totaltime < mintime) {
mintime = totaltime;
loc = x;
}
}
}
cout << clock[loc].hours;
cout << ':';
if (clock[loc].mins < 10) {
cout << 0 << clock[loc].mins;
}
else {
cout << clock[loc].mins;
}
cout << ':';
if (clock[loc].secs < 10) {
cout << 0 << clock[loc].secs;
}
else {
cout << clock[loc].secs;
}
}
Sort the times
Calculate the difference between each two neighbors and the first and last element
Find the maximum difference and remove it (the solution is the left neighbor of this difference)
I am new to programming and trying my hands on Class to class conversion using conversion operator function.
My aim is to convert a 24 hour clock to 12 hour clock using conversion operator function (I should see both 12 and 24 hour clock).
Below is my code, while trying to see the time in 12 hour format it shows garbage value.
What changes should I a make in the code to see the correct time in 12 hours format?
#include<iostream.h>
#include<conio.h>
class Time24
{
public:
int hrs;
int min;
int sec;
void getTime()
{
h:
cout<<"Enter time in hours : " ;
cin>>hrs;
if(hrs > 23 || hrs < 0)
{
cout<<"Hours cannot be greater than 23 or less than 0 "<<endl;
goto h;
}
m:
cout<<"Enter time in minutes : ";
cin>>min;
if(min > 59 || min < 0)
{
cout<<"Minutes cannot be greater than 59 or less than 0"<<endl;
goto m;
}
s:
cout<<"Enter time in seconds : ";
cin>>sec;
if(sec > 59 || sec < 0)
{
cout<<"Seconds cannot be greater than 59 or less than 0"<<endl;
goto s;
}
}
void display()
{
cout<<"Time in 24 hours format = "<<hrs<<":"<<min<<":"<<sec<<endl;
}
};
class Time12
{
public:
int hrs;
int min;
int sec;
Time12()
{
hrs = 0;
min = 0;
sec = 0;
}
operator Time24()
{
Time24 t;
hrs = t.hrs;
min = t.min;
sec = t.sec;
cout<<"In operator function"<<endl;
cout<<"t,hrs ="<<t.hrs<<endl;
cout<<"hrs = "<<hrs<<endl;
if(hrs > 12)
{
hrs = hrs - 12;
}
return t;
}
void display()
{
cout<<"Time in 12 hours format = "<<hrs<<":"<<min<<":"<<sec;
}
};
void main()
{
clrscr();
Time24 t2;
Time12 t1;
t2.getTime();
t2.display();
//t1=t2;
t2=t1;
//t2 = Time24(t1);
t1.display();
getch();
}
I suppose instead of
hrs = t.hrs;
min = t.min;
sec = t.sec;
in Time12::operator Time24() you mean
t.hrs = hrs;
t.min = min;
t.sec = sec;
This is why you are getting garbage. However, I don't think that function does what you want it to do anyway. It defines a conversion from Time12 to Time24, which isn't even possible, as Time12 doesn't know if it's AM or PM. What you want is a operator Time12() in Time24.
I'm trying to design a piece of code that works like this. The user enters a 3 digit number, let's say they chose 653, they also input which numbers in that integer they wish to swap around. For example:
Enter a number and values you wish to swap: "653 2 3"
This then returns the following value:
635 is the new number.
I am trying to do this in a function I called digit_swap. Im not really sure how I to approach this as I'm very new to coding and even newer to coding. I think I have to seperate the integer into the units, tens and hundred components and to do that I did the following:
third = (number % 10);
second = ((number % 100)/10);
first = ((number % 1000)/100);
The only thing is, would I use a bunch of if statements to determine the swapping of the numbers or would it be a loop. I really have no idea how to go about this. As for my code I have the following.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int digit_swap(int number, int InputOne, int InputTwo) {
int first, second, third;
if (number < 100) {
cout << "Please enter a 3 digit integer\n";
exit(0);
}
else if (number >= 1000) {
cout << "Please enter a 3 digit integer\n";
exit(0);
}
else {
third = (number % 10);
second = ((number % 100)/10);
first = ((number % 1000)/100);
}
}
using namespace std;
int main() {
int option_one, option_two;
int number;
cin >> number;
cin >> option_one >> option_two;
digit_swap(number, option_one, option_two);
cout << "New number = " << number;
}
Even when I test to see if it working by adding a return first in the else segment of the if statement it returns nothing. Any help is appreciated, I'm not asking you to do the code for me either.
int digit_swap(int number, int InputOne, int InputTwo) {
int first, second, third;
if (number < 100) {
// DO Something as you are doing
}
else {
third = (number % 10);
number /= 10;
second = (number % 10);
number /= 10;
first = (number % 10);
number /= 10;
}
if(InputOne == 1) {
if(InputTwo == 2) {
number += second*100 + first*10 + third;
}
else if(InputTwo == 3) {
number += third*100 + second*10 + first;
}
else{;}
}
else if(InputOne == 2) {
if(InputTwo == 3) {
number += first*100 + third*10 + second;
}
}
else{;}
return number;
}
I didn't test your code but I think there is an issue with the way you want to procede.
you want to modify "number" by passing it to your function
int digit_swap(int number, int InputOne, int InputTwo) {
int first, second, third;
if (number < 100) {
cout << "Please enter a 3 digit integer\n";
exit(0);
}
else if (number >= 1000) {
cout << "Please enter a 3 digit integer\n";
exit(0);
}
else {
third = (number % 10);
second = ((number % 100)/10);
first = ((number % 1000)/100);
}
}
if you want to modify a variable inside a function and the change can be see outside you will need to use pointer. If you are new to programming I suggest you to do something like this in your main code. The way function works, it will create copy of all your parameter, the change you made on them are not on the originals one.
int main() {
int option_one, option_two;
int number;
cin >> number;
cin >> option_one >> option_two;
int result = digit_swap(number, option_one, option_two);
cout << "New number = " << result;
}
you store in the new result variable the "return of your function"
First you either need to pass number by reference otherwise number in digit_swap is just a copy of number in main(). Your other option is to just call the function like this:
number = digit_swap(number, option_one, option_two);
or by reference
void digit_swap(int & number, int InputOne, int InputTwo);
To help you with swaping i would suggest an int array.
int arr[3];
arr[0] = number / 100;
arr[1] = number / 10;
arr[2] = number % 10;
int temp = arr[InputOne-1];
arr[InputOne-1] = arr[InputTwo-1];
arr[InputTwo-1] = temp;
I hope that helps.
So with this program, basically, I ask for the names of three people, and store those strings in an array. That parts seems to work fine.
After that, I ask for their quarterly reports. So each person gets 4, and it's ordered through the array so that:
Index 0-3 goes to person A
Index 4-7 goes to person B
And index 8-11 goes to person C.
In this second for-loop that processes this second array, I have a list of if/else if statements that determine the name of the person in question that I will be asking for. In the separate function itself, readSales(), I have a similar thing set up to determine which quarter to ask for. This is designed to loop 12 times in order to get all 12 indexes filled.
For some reason, after I input the people's names, the program crashes. Any idea why?
Also, I know "using namespace std;" isn't very popular, but that's how my professor wants it so that's how I have it.
// In this program, I will
// (1) Ask for the names of three salespeople.
// (2) Accept sales for each quarter (for each person).
// (3) Display their name and total sales amount.
// I will use three functions:
// (1) main
// (2) readInfo
// (3) displayInfo
// No global variables, and I will pass data as parameters.
#include <iostream>
#include <string>
using namespace std;
// In order to pass an array through a void function,
// I must create it in the main function.
// So...
string readNames(int); // Function that gathers data from user.
double readSales(string, int);
void displayInfo(); // Function that displays final result.
int main() // Our main function
{
// Create my variables for arrays and final result.
string arrNames[3];
double arrSales[12], result;
// I must call my first function now.
for (int i = 0; i < 3; i++)
{
arrNames[i] = readNames(i); // Successfully gathers all 3 names and stores them in the array. Woo!
}
// Now I must gather the number data, using a double array.
string person = "uninitialized";
int x = 0;
for (x; x < 12; x++);
{
if (x < 4) // setup to ask question
person = arrNames[0];
if (x < 8)
person = arrNames[1];
if (x < 12)
person = arrNames[2];
arrSales[x] = readSales(person, x); // Successfully gathers all 12 quarters and stores them. Yay!
}
cout << arrNames[3];
} // end function main()
string readNames(int count)
{
for (count; count < 3;)
{
string i;
cout << "Please input salesperson " << count + 1 << "'s name: ";
cin >> i;
cout << endl;
return i;
}
return 0;
} // end function readNames()
double readSales(string person, int count) // reading the sales
{
double i; // variable I am returning at the end of function.
int quarter;
if (count == 0 || count == 4 || count == 8)
{
quarter = 1;
}
else if (count == 1 || count == 5 || count == 9)
{
quarter = 2;
}
else if (count == 2 || count == 6 || count == 10)
{
quarter = 3;
}
else if (count == 3 || count == 7 || count == 11)
{
quarter = 4;
}
else
return 0;
cout << "Please input salesperson " << person << "'s sales for Quarter " << quarter << " (Please round to the nearest cent): $" << endl;
cin >> i;
return i;
}
Please remove the semi-colon in the for (x; x < 12; x++);
You can make it like this,
int x = 0;
for (x; x < 12; x++)
{
if ((x >= 0) && ( x <= 3)) // setup to ask question
{
person = arrNames[0];
}
else if ((x >= 4) && (x <= 7))
{
person = arrNames[1];
}
else
{
person = arrNames[2];
}
arrSales[x] = readSales(person, x); // Successfully gathers all 12 quarters and stores them. Yay!
}