Sunday, September 10, 2017

Codility - Lesson 5 Prefix Sums - 2. CountDiv

Source Link:
https://codility.com/programmers/lessons/5-prefix_sums/count_div/

Question:
Write a function:

class Solution { public int solution(int A, int B, int K); }

that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:
{ i : A ≤ i ≤ B, i mod K = 0 }
For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10.
Assume that:
  • A and B are integers within the range [0..2,000,000,000];
  • K is an integer within the range [1..2,000,000,000];
  • A ≤ B.
Complexity:
  • expected worst-case time complexity is O(1);
  • expected worst-case space complexity is O(1).

My Solution:
Notes:
1. need to achieve low complexity O(1), using math equation (low complexity)
2. take "Math.floor" which is the basic number
int num_B = (int) Math.floor( B/K );
int num_A = (int) Math.floor( A/K );
3. number of divisible numbers
int num_div = num_B - num_A;
4. plus one (if A % K == 0), because "A" is also divisble, without "plus", "A" will be deducted
if(A % K == 0)
plus = 1;
5. num_div + plus
num_div = num_div + plus; 

No comments:

Post a Comment

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...