Press "Enter" to skip to content

Posts tagged as “gcd”

花花酱 LeetCode 592. Fraction Addition and Subtraction

Problem

Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result should beĀ irreducible fraction. If your final result is an integer, sayĀ 2, you need to change it to the format of fraction that has denominatorĀ 1. So in this case,Ā 2Ā should be converted toĀ 2/1.

Example 1:

Input:"-1/2+1/2"
Output: "0/1"

Example 2:

Input:"-1/2+1/2+1/3"
Output: "1/3"

Example 3:

Input:"1/3-1/2"
Output: "-1/6"

Example 4:

Input:"5/3+1/3"
Output: "2/1"

Note:

  1. The input string only containsĀ '0'Ā toĀ '9',Ā '/',Ā '+'Ā andĀ '-'. So does the output.
  2. Each fraction (input and output) has formatĀ Ā±numerator/denominator. If the first input fraction or the output is positive, thenĀ '+'Ā will be omitted.
  3. The input only contains validĀ irreducible fractions, where theĀ numeratorĀ andĀ denominatorĀ of each fraction will always be in the range [1,10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
  4. The number of given fractions will be in the range [1,10].
  5. The numerator and denominator of theĀ final resultĀ are guaranteed to be valid and in the range of 32-bit int.

Solution: Math

a/b+c/d = (a*d + b * c) / (b * d)

Time complexity: O(n)

Space complexity: O(1)

C++

C++/class

 

花花酱 LeetCode 878. Nth Magical Number

Problem

A positive integerĀ isĀ magicalĀ if it is divisible by eitherĀ AĀ orĀ B.

Return theĀ N-th magical number.Ā  Since the answer may be very large,Ā return it moduloĀ 10^9 + 7.

Example 1:

Input: N = 1, A = 2, B = 3
Output: 2

Example 2:

Input: N = 4, A = 2, B = 3
Output: 6

Example 3:

Input: N = 5, A = 2, B = 4
Output: 10

Example 4:

Input: N = 3, A = 6, B = 4
Output: 8

Note:

  1. 1 <= NĀ <= 10^9
  2. 2 <= AĀ <= 40000
  3. 2 <= BĀ <= 40000

Solution: Math + Binary Search

Let n denote the number of numbers <= X that are divisible by eitherĀ AĀ orĀ B.

n = X / A + X / B – X / lcm(A, B) = X / A + X / B – X / (A * B / gcd(A, B))

Binary search for the smallest X such that n >= N

Time complexity: O(log(1e9*4e5)

Space complexity: O(1)