How to Determine How many cycles it would take to get a given value to 0 by decreasing it by a given amount - for-loop

This is my problem, i need to take double onHand and reduce it by the double consume, then determine how many cycles it would take to reach 0. then use Math.Round 3 to round it to 3 decimal points.
public static int Test4(double onHand, double consume)
{
int answer = 1;
for (int i = (int)(consume); i > onHand; i--)
{
answer -= (int)onHand;
}
return answer;
}
I tried creating multiple variables like introducing decimals, casting the doubles into floats and ints but i can only get to the point where my answer outputs the int of the onHand.

You just have to make a division.
Assuming onHand is 3.02 and consume is 0.24, you divide them like onHand / consume and that will result in 12.583333. You will have to ceil or round-up the value (13). That is the number of times it'll go trough the loop to reach or pass 0.
Example
public static int Test4(double onHand, double consume)
{
double answer = (decimal)onHand / (decimal)consume;
return (int) Math.Ceiling(answer);
}
I'm no expert on C# so I don't know if the casting is neccesary.

public static int Test4(double onHand, double consume)
{
int answer = 1;
for (int i = 0; i < consume; i++)
{
answer = (int)((decimal)onHand / (decimal)consume);
}
return answer;
}

Related

Find the missing coordinate of rectangle

Chef has N axis-parallel rectangles in a 2D Cartesian coordinate system. These rectangles may intersect, but it is guaranteed that all their 4N vertices are pairwise distinct.
Unfortunately, Chef lost one vertex, and up until now, none of his fixes have worked (although putting an image of a point on a milk carton might not have been the greatest idea after all…). Therefore, he gave you the task of finding it! You are given the remaining 4N−1 points and you should find the missing one.
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
Then, 4N−1 lines follow. Each of these lines contains two space-separated integers x and y denoting a vertex (x,y) of some rectangle.
Output
For each test case, print a single line containing two space-separated integers X and Y ― the coordinates of the missing point. It can be proved that the missing point can be determined uniquely.
Constraints
T≤100
1≤N≤2⋅105
|x|,|y|≤109
the sum of N over all test cases does not exceed 2⋅105
Example Input
1
2
1 1
1 2
4 6
2 1
9 6
9 3
4 3
Example Output
2 2
Problem link: https://www.codechef.com/problems/PTMSSNG
my approach: I have created a frequency array for x and y coordinates and then calculated the point which is coming odd no. of times.
#include <iostream>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--)
{
long int n;
cin>>n;
long long int a[4*n-1][2];
long long int xm,ym,x,y;
for(int i=0;i<4*n-1;i++)
{
cin>>a[i][0]>>a[i][1];
if(i==0)
{
xm=abs(a[i][0]);
ym=abs(a[i][1]);
}
if(i>0)
{
if(abs(a[i][0])>xm)
{
xm=abs(a[i][0]);
}
if(abs(a[i][1])>ym)
{
ym=abs(a[i][1]);
}
}
}
long long int frqx[xm+1],frqy[ym+1];
for(long long int i=0;i<xm+1;i++)
{
frqx[i]=0;
}
for(long long int j=0;j<ym+1;j++)
{
frqy[j]=0;
}
for(long long int i=0;i<4*n-1;i++)
{
frqx[a[i][0]]+=1;
frqy[a[i][1]]+=1;
}
for(long long int i=0;i<xm+1;i++)
{
if(frqx[i]>0 && frqx[i]%2>0)
{
x=i;
break;
}
}
for(long long int j=0;j<ym+1;j++)
{
if(frqy[j]>0 && frqy[j]%2>0)
{
y=j;
break;
}
}
cout<<x<<" "<<y<<"\n";
}
return 0;
}
My code is showing TLE for inputs <10^6
First of all, your solution is not handling negative x/y correctly. long long int frqx[xm+1],frqy[ym+1] allocated barely enough memory to hold positive values, but not enough to hold negative ones.
It doesn't even matter though, as with the guarantee that abs(x) <= 109, you can just statically allocate a vector of 219 elements, and map both positive and negative coordinates in there.
Second, you are not supposed to buffer the input in a. Not only is this going to overflow the stack, is also entirely unnecessary. Write to the frequency buckets right away, don't buffer.
Same goes for most of these challenges. Don't buffer, always try to process the input directly.
About your buckets, you don't need a long long int. A bool per bucket is enough. You do not care even the least how many coordinates were sorted into the bucket, only whether the number so far was even or not. What you implemented as a separate loop can be substituted by simply toggling a flag while processing the input.
I find the answer of #Ext3h with respect to the errors adequate.
The solution, giving that you came on the odd/even quality of the problem,
can be done more straight-forward.
You need to find the x and y that appear an odd number of times.
In java
int[] missingPoint(int[][] a) {
//int n = (a.length + 1) / 4;
int[] pt = new int[2]; // In C initialize with 0.
for (int i = 0; i < a.length; ++i) {
for (int j = 0; j < 2; ++j) {
pt[j] ^= a[i][j];
}
}
return pt;
}
This uses exclusive-or ^ which is associative and reflexive 0^x=x, x^x=0. (5^7^4^7^5=4.)
For these "search the odd one" one can use this xor-ing.
In effect you do not need to keep the input in an array.

Quantum algorithm for summation of superposition

Im not at all sure how to word this question, but I will try my best. Im wanting to have examples of quantum algorithms that can complete logical parallel tasks. It extends beyond simply summation, for example multiplication, or finding the highest value, or a value closest to a given fixed value.
I know quantum algorithms can very easily "input" multiple states into a function/circuit and get a superposition of all answers, and even select specific desired outputs with grover's algorithm, but is it possible to incorporate multiple superposition into a final classical answer? Since there is no order to each "probability", obviously operations that depend on sequence are not possible.
Im trying to get into the mindset of how to make use of a quantum computer, and design circuits for it. Im not interested in theory or equations, just raw circuit/qasm diagrams.
Such examples that Im trying to refer to can be written as pseduo code like below
struct possibility {
float weight;
int value;
};
int summation(possibility[] input) {
int result = 0;
for (int i = 0; i < sizeof(input); i++) {
result += input[i].value * input[i].weight;
}
return result;
}
int multiplication(possibility[] input) {
int result = 1;
for (int i = 0; i < sizeof(input); i++) {
result *= input[i].value * input[i].weight;
}
return result;
}
int findClosest(possibility[] input, int toValue) {
int result = input[0].value;
int resultDistance = abs(toValue - result) * input[0].weight;
for (int i = 1; i < sizeof(input); i++) {
int distance = abs(toValue - input[i].value) * input[i].weight;
if (distance < resultDistance) {
result = input[i].value;
resultDistance = distance;
}
}
return result;
}
Sorry for my poor wording. Im not at all sure how to word this question better with my tiny knowledge in this subject. Any help at all is appreciated!

Get the last 1000 digits of 5^1234566789893943

I saw the following interview question on some online forum. What is a good solution for this?
Get the last 1000 digits of 5^1234566789893943
Simple algorithm:
1. Maintain a 1000-digits array which will have the answer at the end
2. Implement a multiplication routine like you do in school. It is O(d^2).
3. Use modular exponentiation by squaring.
Iterative exponentiation:
array ans;
int a = 5;
while (p > 0) {
if (p&1) {
ans = multiply(ans, a)
}
p = p>>1;
ans = multiply(ans, ans);
}
multiply: multiplies two large number using the school method and return last 1000 digits.
Time complexity: O(d^2*logp) where d is number of last digits needed and p is power.
A typical solution for this problem would be to use modular arithmetic and exponentiation by squaring to compute the remainder of 5^1234566789893943 when divided by 10^1000. However in your case this will still not be good enough as it would take about 1000*log(1234566789893943) operations and this is not too much, but I will propose a more general approach that would work for greater values of the exponent.
You will have to use a bit more complicated number theory. You can use Euler's theorem to get the remainder of 5^1234566789893943 modulo 2^1000 a lot more efficiently. Denote that r. It is also obvious that 5^1234566789893943 is divisible by 5^1000.
After that you need to find a number d such that 5^1000*d = r(modulo 2^1000). To solve this equation you should compute 5^1000(modulo 2^1000). After that all that is left is to do division modulo 2^1000. Using again Euler's theorem this can be done efficiently. Use that x^(phi(2^1000)-1)*x =1(modulo 2^1000). This approach is way faster and is the only feasible solution.
The key phrase is "modular exponentiation". Python has that built in:
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> help(pow)
Help on built-in function pow in module builtins:
pow(...)
pow(x, y[, z]) -> number
With two arguments, equivalent to x**y. With three arguments,
equivalent to (x**y) % z, but may be more efficient (e.g. for ints).
>>> digits = pow(5, 1234566789893943, 10**1000)
>>> len(str(digits))
1000
>>> digits
4750414775792952522204114184342722049638880929773624902773914715850189808476532716372371599198399541490535712666678457047950561228398126854813955228082149950029586996237166535637925022587538404245894713557782868186911348163750456080173694616157985752707395420982029720018418176528050046735160132510039430638924070731480858515227638960577060664844432475135181968277088315958312427313480771984874517274455070808286089278055166204573155093723933924226458522505574738359787477768274598805619392248788499020057331479403377350096157635924457653815121544961705226996087472416473967901157340721436252325091988301798899201640961322478421979046764449146045325215261829432737214561242087559734390139448919027470137649372264607375942527202021229200886927993079738795532281264345533044058574930108964976191133834748071751521214092905298139886778347051165211279789776682686753139533912795298973229094197221087871530034608077419911440782714084922725088980350599242632517985214513078773279630695469677448272705078125
>>>
The technique we need to know is exponentiation by squaring and modulus. We also need to use BigInteger in Java.
Simple code in Java:
BigInteger m = //BigInteger of 10^1000
BigInteger pow(BigInteger a, long b) {
if (b == 0) {
return BigInteger.ONE;
}
BigInteger val = pow(a, b/2);
if (b % 2 == 0)
return (val.multiply(val)).mod(m);
else
return (val.multiply(val).multiply(a)).mod(m);
}
In Java, the function modPow has done it all for you (thank Java).
Use congruence and apply modular arithmetic.
Square and multiply algorithm.
If you divide any number in base 10 by 10 then the remainder represents
the last digit. i.e. 23422222=2342222*10+2
So we know:
5=5(mod 10)
5^2=25=5(mod 10)
5^4=(5^2)*(5^2)=5*5=5(mod 10)
5^8=(5^4)*(5^4)=5*5=5(mod 10)
... and keep going until you get to that exponent
OR, you can realize that as we keep going you keep getting 5 as your remainder.
Convert the number to a string.
Loop on the string, starting at the last index up to 1000.
Then reverse the result string.
I posted a solution based on some hints here.
#include <vector>
#include <iostream>
using namespace std;
vector<char> multiplyArrays(const vector<char> &data1, const vector<char> &data2, int k) {
int sz1 = data1.size();
int sz2 = data2.size();
vector<char> result(sz1+sz2,0);
for(int i=sz1-1; i>=0; --i) {
char carry = 0;
for(int j=sz2-1; j>=0; --j) {
char value = data1[i] * data2[j]+result[i+j+1]+carry;
carry = value/10;
result[i+j+1] = value % 10;
}
result[i]=carry;
}
if(sz1+sz2>k){
vector<char> lastKElements(result.begin()+(sz1+sz2-k), result.end());
return lastKElements;
}
else
return result;
}
vector<char> calculate(unsigned long m, unsigned long n, int k) {
if(n == 0) {
return vector<char>(1, 1);
} else if(n % 2) { // odd number
vector<char> tmp(1, m);
vector<char> result1 = calculate(m, n-1, k);
return multiplyArrays(result1, tmp, k);
} else {
vector<char> result1 = calculate(m, n/2, k);
return multiplyArrays(result1, result1, k);
}
}
int main(int argc, char const *argv[]){
vector<char> v=calculate(5,8,1000);
for(auto c : v){
cout<<static_cast<unsigned>(c);
}
}
I don't know if Windows can show a big number (Or if my computer is fast enough to show it) But I guess you COULD use this code like and algorithm:
ulong x = 5; //There are a lot of libraries for other languages like C/C++ that support super big numbers. In this case I'm using C#'s default `Uint64` number.
for(ulong i=1; i<1234566789893943; i++)
{
x = x * x; //I will make the multiplication raise power over here
}
string term = x.ToString(); //Store the number to a string. I remember strings can store up to 1 billion characters.
char[] number = term.ToCharArray(); //Array of all the digits
int tmp=0;
while(number[tmp]!='.') //This will search for the period.
tmp++;
tmp++; //After finding the period, I will start storing 1000 digits from this index of the char array
string thousandDigits = ""; //Here I will store the digits.
for (int i = tmp; i <= 1000+tmp; i++)
{
thousandDigits += number[i]; //Storing digits
}
Using this as a reference, I guess if you want to try getting the LAST 1000 characters of this array, change to this in the for of the above code:
string thousandDigits = "";
for (int i = 0; i > 1000; i++)
{
thousandDigits += number[number.Length-i]; //Reverse array... ¿?
}
As I don't work with super super looooong numbers, I don't know if my computer can get those, I tried the code and it works but when I try to show the result in console it just leave the pointer flickering xD Guess it's still working. Don't have a pro Processor. Try it if you want :P

Count the number of consecutive zeros in a number WITHOUT using loops

I found this to be asked as an interview question. While it is fairly trivial to solve using bit masking and loops, any idea on how this can be done without loops? While I'm looking for an algorithm, any code would be appreciated as well.
The options I see for solving the problem without loops are bit hacks, recursion and loop unrolling.
Solving this with bit hacks seems quite difficult - most likely something only the most skilled bit hackers would be able to figure out in the time limit of an interview, or really figure out at all, but it's possible that that's who they were looking for.
Loop unrolling is just a silly solution.
So that leaves recursion.
Below is a recursive solution in Java.
It basically maintains the current count of consecutive zeros and also the best count, checks the last digit (i.e. checks the number modulo 10), sets these values appropriately and recurses on the number without the last digit (i.e. divided by 10).
I assumed we're talking about zeros in the decimal representation of the number, but converting this to use the binary representation is trivial (just change 10 to 2).
public static int countMaxConsecutiveZeros(int number)
{
return countMaxConsecutiveZeros(number, 0, 0);
}
private static int countMaxConsecutiveZeros(int number, int currentCount, int bestCount)
{
if (number == 0)
return bestCount;
if (number % 10 == 0)
currentCount++;
else
{
bestCount = Math.max(bestCount, currentCount);
currentCount = 0;
}
return countMaxConsecutiveZeros(number / 10, currentCount, bestCount);
}
public static void main(String[] args)
{
System.out.println(countMaxConsecutiveZeros(40040001)); // prints 3
}
Here's a roughly equivalent loop-based solution, which should provide a better understanding of the recursive solution:
private static int countMaxConsecutiveZerosWithLoop(int number)
{
int currentCount = 0, bestCount = 0;
while (number > 0)
{
if (number % 10 == 0)
currentCount++;
else
{
bestCount = Math.max(bestCount, currentCount);
currentCount = 0;
}
number /= 10;
}
return bestCount;
}
I don't know if this is what they were looking for, but here is a recursive solution.
I used two recursions, one comparing the current string of zeros to the record, and another recursion calculating the current string of zeros.
public class countconsecutivezeros{
public static void main(String[] Args){
int number = 40040001; // whatever the number is
System.out.println(consecutivezeros(number, 0));
}
public static int consecutivezeros(int number, int max){
if (number != 0){
if (max < zerosfrompoint(number)) max = zerosfrompoint(number);
return consecutivezeros(number/10, max);
}
return max;
}
public static int zerosfrompoint(int number){
int zeros = 0;
if ((number != 0) && ((number/10)*10 == number)){
zeros++;
System.out.println(zeros);
return zeros + zerosfrompoint(number/10);
}
return zeros;
}
}

How to get the (Greatest Common Divisor)GCD of Doubles

This is a simple task but i can't seem to figure out how to do it
Here is a sample function structure
private double GetGCD(double num1, double num2)
{
//should return the GCD of the two double
}
test data
num1 = 6;
num2 = 3;
*return value must be 3*
num1 = 8.8;
num2 = 6.6;
*return value must be 2.2*
num1 = 5.1;
num2 = 8.5;
*return value must be 1.7*
note: maximum decimal places is 1.
programming language is not important. i just need the algorthm
please help.. thank you!
If you have only one decimal place, multiply the numbers by 10, convert them to integers and run an integer GCD function.
This will also save you floating point precision errors.
Quoting this answer, the base Euclidean algorithm in Python (for integers!) is:
def gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a%b
return a
So, your code should be something like:
def gcd_floats(x,y):
return gcd( int(x*10), int(y*10) )/10
When it's 8.8 and 6.6 then you can find the GCD of 88 and 66 and then divide it by 10.
There are zillions of places on the web to find code for the GCD function. Since, strictly speaking, it is only defined on integers, I suggest you multiply your doubles by 10, work out the GCD and divide the result by 10. This will save you a world of pain arising from using the wrong datatype.
here is a source from google with some java code : http://www.merriampark.com/gcd.htm this is pretty comprehensive.
There is no such thing as the GCD of a number which is not discrete. However, your case is more specific. If your input is not a Double, but a Decimal, then you can convert it to a Fraction, multiply the denominators, find the GCD of the numerators and divide back down. That is:
8.800 = 8800/1000 = 44/5 (by GCD)
6.600 = 6600/1000 = 33/5 (by GCD)
5.100 = 5100/1000 = 51/10
8.500 = 8500/1000 = 17/2
It's useful to simplify the fractions in this step in order to avoid our numbers getting too large.
Move to a common denominator:
44*5/5*5 = 220/25
33*5/5*5 = 165/25
51*2/2*10 = 102/20
17*10/2*10 = 170/20
GCD of numerator:
gcd(165,220) = 55
gcd(102,170) = 34
So answers are 55/25 and 34/20.
Using 2 methods
The traditional division method
Euclid's method
class GCD
{
public static void main(String[] args)
{
int a = (int)(1.2*10);
int b = (int)(3.4*10);
System.out.println((float)gcd(a, b)/10);
}
// 1
public static int gcd(int a, int b)
{
if(b==0)
return a;
else
return gcd(b, (int)a%b);
}
// 2
public static int gcd(int a, int b)
{
int k,i;
if(a>b)
k = b;
else
k = a;
for(i=k; i>=2; i--)
{
if( (a%i==0)&&(b%i==0) )
{
break;
}
}
return i;
}
}

Resources