GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — coding-problems/Math/count_divisibles_in_range.py at master · CROXX-Code/coding-problems

Expand file tree

/

count_divisibles_in_range.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
63 lines (47 loc) · 1.67 KB
/

count_divisibles_in_range.py

Copy path

File metadata and controls

63 lines (47 loc) · 1.67 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
'''
Count Divisibles in Range
Let us take a breather and tackle a problem so simple that its solution needs only a couple of
conditions, but not even any loops, let alone anything even more fancy. The difficulty is coming up
with the conditions that cover all possible cases of this problem exactly right, including all of the
potentially tricksy edge and corner cases, and not be off-by-one. Given three integers start, end
and n so that start <= end, count and return how many integers between start and end,
inclusive, are divisible by n.
Input: 7, 28, 4
Output: 6
=========================================
Find the close divisible to start (the smallest divisible in the range), calculate the difference between
that number and the end of the range, and in the end divide the difference by N.
Time Complexity: O(1)
Space Complexity: O(1)
'''
############
# Solution #
############
def count_divisibles_in_range(start, end, n):
# find the next start number divisable by n
start += (n - (start % n)) % n
if start > end:
# in this case there are no numbers divisable by n
return 0
return 1 + ((end - start) // n)
###########
# Testing #
###########
# Test 1
# Correct result => 6
print(count_divisibles_in_range(7, 28, 4))
# Test 2
# Correct result => 9
print(count_divisibles_in_range(-77, 19, 10))
# Test 3
# Correct result => 0
print(count_divisibles_in_range(-19, -13, 10))
# Test 4
# Correct result => 199999999999
print(count_divisibles_in_range(1, 10**12 - 1, 5))
# Test 5
# Correct result => 200000000000
print(count_divisibles_in_range(0, 10**12 - 1, 5))
# Test 6
# Correct result => 200000000001
print(count_divisibles_in_range(0, 10**12, 5))
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.