HackerEarth's basic programming solutions( Conject-It !, Play with numbers, Divisibility ) :
Problem 33: Conject-It !
Solution: (in c++)
( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)
Are you guys wondering why i haven't included the statement cout<<"NO"<<endl; in case n doesn't become equal to 1 in the last operation. If yes then , n will never become other than 1 in last operation. You can take any number and try it yourself.
Reason:
If n becomes odd , we convert it into even by this operation: n=(3*n)+1 and if even we divide it by 2 which eventually gives us 1 in the end.
Problem 34: Play with numbers
Solution: (in c++)
( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)
let the given array is:
But for this question , we will make a new array such that it's zeroth element is 1 , first element is sum of the elements in the first circle and the second element is sum of element in second circle and so on.
so finally our array will look like this:
now if l = 1, we can directly write the mean in that case i.e a[r-1]/r i.e sum of the elements of a circle depending on the value of r divided by r.
For example: if r = 3 , we have to consider the 3rd circle i.e element at index 2 in the final array which represents the sum of elements of the 3rd circle.
Therefore answer = 6/2 = 3
In case, l is not equal to 1: we use this formula --> a[r-1]-a[l-2]/r-l+1
This is obvious , for example: l = 2 and r =4 therefore the sum in this case will be 4th circle - 1st circle i.e a[3]-a[0].
Therefore answer = a[3]-a[0]/(4-2+1) = 9/3 = 3
How to decide which two circles?
The two circles will be r value and l-1 value and therefore the corresponding index are r-1 and l-2.
Problem 35: Divisibility
Solution: (in c++)
( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)
This question is much more than you think of. You will be wondering right now (if you have analyzed this code) what's the reason for p here when sum at last gives us the digit we want, then we only have to check whether sum%10 = 0 or not.
The reason of using p is , take for example n = 38716 , therefore 38716 numbers and then sum is trying to store a 38716 digit number . In this case integer overflow will take place and your program will fail.
Explanation -
p = sum%10 , p will only become 0 when sum becomes a multiple of 10. Therefore sum will continue to become a number(made up of last digits ) till in sum at the end 0 comes. When 0 comes the sum is reset again to 0.
This reset of sum , prevents the sum from becoming a gigantic number.
Guys , if you have any queries related to a question or need more explanation, comment down below!
Comments
Post a Comment