Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I tried solving a question on hackerearth and i was not able to solve it so i saw editorial.They gave only code without explanation.Can u expain logic behind why gcd used here?
Question:
Scooby and all of his friends have gathered for a party. There are N friends present. Scooby is really happy to see all of his friends in one place and is excited to greet them.
All N friends are seated in a circle, and are numbered from 0 to N-1. Scooby is initially sitting beside the Ath friend. After greeting one friend, he goes clockwise to the Bth next friend, sits next to him and greets him. He repeats this till he returns to the Ath friend.
In his excitement, it is possible that Scooby misses out on greeting some friends. Your job is to find the number of friends (including A) that Scooby will have greeted before reaching back to A.
Solution given:
int main()
{
int T;
cin>>T;
while(T--)
{
long long N,A,B;
cin>>A>>B>>N;
long long g=gcd(B,N);
cout<<N/g<<endl;
}
return 0;
}
To explain the solution of the above problem I will first show that the answer is - LCM(B,N)/B and then show you how this is equal to N/GCD(B,N).
First Part-
Now assume that when it again reaches A after following the above mentioned steps he would have greeted f friends.(Note no two friends greeted through the above mentioned procedure can be same). Moreover, assume that when he reached A he would have made r rounds of the circle.
Now we can say that -
f * B = r * N = C.
Let this be equal to some constant C. Clearly C is some multiple of B and N moreover, it is the Lowest Common Multiple(LCM) of B and N(as we want to give answer as soon as it reaches for the first time).
So f = LCM(B,N)/B. Note f is the number of friends he greeted so it is the required answer.
Second Part-
For two positive integers a and b with their GCD and LCM g and l respectively, we have the following relation - a*b = g*l.
From the above relation we can say that -
LCM(B,N)*GCD(B,N) = B*N
=> LCM(B,N)/B = N/GCD(B,N)
So finally we have our answer = LCM(B,N)/B = N/GCD(B,N).
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Recently I have started looking into C++ from the basics and got to know (to my surprise) that I can give series of expressions in a single line separated by commas in some cases as below
//it'll execute all the expressions mentioned after condition seperated by comma
for(int i=0;condition;++i,++x,cout<<"in for loop"<<endl,z = z*2);
(x>y)? ++z,z1 = z*2, cout<<"printing statement"<<endl:cout<<"condition failed"<<endl,z = z/2;
Here, I have a confusion after this is working. Is it safe to code in that way or is there any problem coding in such a way?
Please clarify!!!
Correct me if i'm wrong anywhere, I'm just curious to know why most of the programmers don't use this way (I haven't seen such kind of lines anywhere)
The comma operator , evaluates each of its operands in sequence. In standardese, there is a sequence point between the evaluation of the left operand and the right operand.
In a expression which contains a comma operator, the value of the left operand is discarded and the expression takes on the value of the right operand. In both of the examples above, the comma operator is used in a void context, so none of the values are used.
So a statement like this where the value of the comma operator is not used:
exp1, exp2, exp3, exp4;
Is equivalent to the following sequence of statements:
exp1; exp2; exp3; exp4;
The first example is equivalent to the following:
for(int i=0;condition;) {
++i;
++x;
cout<<"in for loop"<<endl;
z = z*2;
}
And the second example:
if (x>y) {
++z;
z1 = z*2;
cout<<"printing statement"<<endl;
} else {
cout<<"condition failed"<<endl;
z = z/2;
}
Note that this is considerably more readable that the one-line versions. It's also easier to debug. Since debuggers typically step through code a line at a time, it breaks up the flow and is more granular.
Not indenting and spacing your code is not less costly regarding performance. It is unreadable, confusing and a pain to understand for you and for anyone who'd have to work with it.
Lot of people will prefer a well-syntaxed, beautifully and efficiently-indented code than a top-performance one. You can modify, debug and refract a code which might not work but has the advantage to be understandable.
On the other hand, very few codes remain unchanged and stay unread. There will always be a time when someone, may be you, will have to read it again and if it looks like the one if your OP, it will be very time costly to do.
It is allowed. In my opinion and i say without a reference that in general other programmers do not find your 'for' loop very readable. Sometimes in a for loop you want to do other things then just for (int i = 0; i < 10; ++i){"do something"}For example increment 'i' in every loop with two. Reading code should be like reading a text. If you are reading a book you do not want it to be unnecessary difficult.
Your other question was about the safety of the statement. The biggest problem with the code is that you might get confused about what you are doing exactly. Bugs are caused by human errors (computers are deterministic and are executing machine code which ultimately has been written by a human) and the question about safety mainly depends on how you define it.
To give you some tips. When i just started programming C++ i looked a lot on CPP reference. I will give you a link where you can read about the syntax and what is allowed/possible. On this website there are quite a lot of examples on all kinds of statements. They will in general not put 5 or 6 operations within in a single line. If there are more variables that you want to change then you might want to do that in the scope of the for loop so it will be more readable instead of inside the for loop.
http://en.cppreference.com/w/cpp/language/for
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I participated in Codeforces Round #396 (Div. 2) yesterday.
The (A) problem seemed pretty advanced in my opinion when I read it.
I tried solving it all the competition time yesterday and some time today.
I came up with a 200 lines long(half-working) solution. And then I gave up.
I looked what other people wrote there and I saw max 20 lines long code that seems magic to me.
The problem asks you to output the length of the longest uncommon subsequence of letters from two strings.
You can read the full problem here:
http://codeforces.com/contest/766/problem/A
#include<bits/stdc++.h>
using namespace std;
string a,b;
int main(){
cin>>a>>b;
printf("%d",a==b?-1:max(a.size(),b.size()));
return 0;
}
This is all the code used to solve the problem, and I really want to know how that one line of code
printf("%d",a==b?-1:max(a.size(),b.size()));
can solve this "advanced" task?
If the two strings are equal, there is no "uncommon subsequence". If they are not equal, neither one is a subsequence of the other, but each one is a subsequence of itself, so each one is an "uncommon subsequence". The longer of the two is the longest "uncommon subsequence", and its length is the correct answer. If the two are not equal but have the same length, then each one is an "uncommon subsequence" and the length of the longest is just the length of either one.
Don't get tangled up in what you (or any other reasonable person) think a "subsequence" is. The problem defines "uncommon subsequence", and all you have to do is apply its definition. This "problem" is about word play, not coding.
It does not seem to solve the task at hand. It just outputs -1 when the strings are equal and the length of the longer string when they are not different. However, the problem asks for the longest uncommon sequence. It would fail with the inputs abc and abcd to give the answer 1 would rather give 4.
What the line does is the following:
It checks whether a == b, whether the strings are equal.
If they are equal, the condition A is true in the ternary operator A ? B : C, so that expression will evaluate to B which is just -1 here.
If they are not equal, it will evaluate to C which is the maximum of the two string lengths, so it will be length of the longer string.
The value of the ternary expression is then printed, albeit without a newline, which is a bit bad.
So the code is so short because it only solves the problem for a few cases but not the general case.
printf ("%d", a == b ? -1 : max (a.size (), b.size ()));
is equivalent to
if (a == b) {
printf ("%d", -1);
}
else {
if (a.size () > b.size ()) {
printf ("%d", a.size ());
}
else {
printf ("%d", b.size());
}
}
BTW That's only a small step in solving the problem...
[CORRECTION]
IT DOES SOLVE THE WHOLE PROBLEM (See answer of Pete Becker)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Why does List MakeEmpty(List L) have to be written in a form like:
List
MakeEmpty(List L)
in Mark Allens Book?
This is just a matter of styling preference; the command here is the same regardless of whether you write:
List
MakeEmpty(List L)
or
List MakeEmpty(List L)
It really doesn't make a difference besides changing the readability of the code. The author of the book you mentioned may find adding some whitespace more readable compared to the conventional method you compared it to.
One way you can differentiate between whitespace and a real compiling difference is the semicolon. Wherever there is a semicolon, the line terminates. In your case, if there was:
List; // Notice semicolon here
MakeEmpty(List L)
Then this would have changed the code (the syntax is wrong here as it changes the original meaning of the code, but I just wanted to make my point with this example).
Adding whitespace makes the code more readable to the programmer; it adds to the style, especially if it is being presented to a larger audience. The amount of whitespace preferred varies from person to person.
I tried to make the simplest example possible here: the main() function. See the 2 ways I wrote it:
Method 1:
int // Return type of function on different line from function name and arguments for function declaration
main(void)
{
cout << "hello" << endl;
return 0;
}
Method 2:
int main(void) // Return type of function on same line as function name and arguments for function declaration
{
cout << "hello" << endl;
return 0;
}
Just like your function declaration, here, the return value data type's position is changed between the 2 samples of code. However, the output is the same: It outputs hello followed by an endline.
Hope this helps. If I've made a mistake anywhere, or you have further questions, ask me in the comments box.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to figure this one out on my own and I can't.
The professor is asking for this.
User will define the length of the sequence.
User will then enter numbers from any range being both neg and pos.
The program:
Find the two largest numbers and display in descending order.
Find the two smallest numbers and display in ascending order.
Can't use sort or arrays.
I have an outline but, my head just wants to use arrays..... I don't see this simple without an array. Confused. I'm a beginner. I just want help. Advice? Tutor?
Start with a solution to an easier problem, and grow it into a solution to the actual problem that you are solving:
Write a program that finds and prints the largest number entered by the user. This is easy to do with a single variable keeping track of "high watermark"
Modify your program to keep track of the smallest number as well. You can do it by adding another variable, and keeping track of the "low watermark".
The challenge in both tasks above is the initial value of the high/low watermark. This is a common source of errors; there are multiple Q&As on SO explaining the fix.
Now for the fun part:
Modify your program to keep track of the second-largest number by "demoting" the number that was previously considered largest to second-largest each time that you find a number that is larger than the largest one, and by replacing the second-largest when you find a value above it that does not exceed the largest value.
This would require you to write a couple of if statements.
Finally, modify your program to keep track of the second-smallest number by applying the "mirror image" of the algorithm above.
Algorithm ("Find the two largest numbers in a sequence without storing the sequence")
(I decided to undelete this answer. It might be helpful to OP to get away from the array frame of mind)
Input: A sequence of values S.
Output: Values Max and SecondMax.
The consumed, current value of S is E
1 : Set Max to E
2 : Set SecondMax to E (Second value in S)
3 : If Max < SecondMax -> Swap Max and SecondMax.
4 : while ( e:= E exists)
4.1 : If ( e > Max ) SecondMax := Max, Max := e
4.1.1 : Else If ( e > SecondMax ) SecondMax := e
This is trivially extended to the minimums.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
oops, I am not talking about Object Operator, some call it arrow, some call it thingy...
today, while studying DISCRETE STRUCTURES, teacher told us,
if p then q , this is a conditional statement and its written as p -> q ( p implies q),
my question was, what this sign is called, teacher says its if and then sign, then say, its implies sign, but I dont feel it right...
can somebody tell me what this sign is called?? can somebody explain it ? as I was caught in the sign only, I wasnt even able to listen what the teacher was telling about this conditional statement...( teacher sent me out of class saying YOU ARE ASKING FOOLISH QUESTIONSS :( )
One Request..I dont know where to Put this question...as discrete structures relates to programming, so putting my question right here, Forgive me for this if I am at wrong place ( no down-voting , rather please shift this question to approperiate place )
Wikipedia titles it the Material Conditional operator, though I've usually called it the implication operator. In my discrete structures class, we generally read it as either "if p then q" or "p implies q".
For completeness sake, here's the truth table:
p | q | p -> q
--------------
T | T | T
T | F | F
F | T | T
F | F | T
Maybe you could call it simply the arrow sign. We used to say it like "p arrow q".
you can understand it by this way,
p -> q // p derives q. You can reach to q if you are given p.
// q is obtainable from p.