how many positive integers are divisible by a number d in range [x,y]?

本文介绍了一种高效算法,用于计算指定范围内整数倍数的数量。通过巧妙地利用数学运算,可以在常数时间内得出结果,适用于大规模数据处理。

It can be done in O(1): find the first one, find the last one, find the count of all other.

I'm assuming the range is inclusive. If your ranges are exclusive, adjust the bounds by one:

  • find the first value after x that is divisible by z. You can discard x:

    x_mod = x % z;
    
    if(x_mod != 0)
      x += (z - x_mod);
    
  • find the last value before y that is divisible by y. You can discard y:

    y -= y % z;
    
  • find the size of this range:

    if(x > y)
      return 0;
    else
      return (y - x) / z + 1;
    

If mathematical floor and ceil functions are available, the first two parts can be written more readably. Also the last part can be compressed using math functions:

 x = ceil  (x, z);
 y = floor (y, z);
 return max((y - x) / z + 1, 0);

if the input is guaranteed to be a valid range (x >= y), the last test or max is unneccessary:

 x = ceil  (x, z);
 y = floor (y, z);
 return (y - x) / z + 1;
share improve this answer
 

You could make a function f to calculate the number of multiples for any number n, then

  • calculate a = f(y)
  • calculate b = f(x-1) since x is included (x > 0)
  • the result is a - b

The algorithm (function f) to calculate the number of multiples of base b for a number n is simple

multiples = n / b      ( '/' is integer division)

That should give you enough material to build the actual functions.
The functions are of course O(1)

The whole algorithm comes as (x > 0)

function f(n, b) {
    return n / b
}

print f(y) - f(x-1)

Examples of results you should find

  • [1, 1000] ÷ 6 => 166
  • [100, 1000000] ÷ 7 => 142843
  • [777, 777777777] ÷ 7 => 111111001
share improve this answer
 
1 
I don't understand "function f to calculate the number of multiples for any number n". Do you mean integer division? –  Jan Dvorak  May 5 '13 at 6:29
 
Yes, (integer division) is written below the multiples line –  ringø  May 5 '13 at 6:30
 
very clever!!!! –  Bin Chen  May 5 '13 at 6:32

I also encountered this on Codility. It took me much longer than I'd like to admit to come up with a good solution, so I figured I would share what I think is an elegant solution!

Straightforward Approach 1/2:

O(N) time solution with a loop and counter, unrealistic when N = 2 billion.

Awesome Approach 3:

We want the number of digits in some range that are divisible by K.

Simple case: assume range [0 .. n*K], N = n*K

N/K represents the number of digits in [0,N) that are divisible by K, given N%K = 0 (aka. N is divisible by K)

ex. N = 9, K = 3, Num digits = |{0 3 6}| = 3 = 9/3

Similarly,

N/K + 1 represents the number of digits in [0,N] divisible by K

ex. N = 9, K = 3, Num digits = |{0 3 6 9}| = 4 = 9/3 + 1

I think really understanding the above fact is the trickiest part of this question, I cannot explain exactly why it works. The rest boils down to prefix sums and handling special cases.


Now we don't always have a range that begins with 0, and we cannot assume the two bounds will be divisible by K. But wait! We can fix this by calculating our own nice upper and lower bounds and using some subtraction magic :)

  1. First find the closest upper and lower in the range [A,B] that are divisible by K.

    • Upper bound (easier): ex. B = 10, K = 3, new_B = 9... the pattern is B - B%K
    • Lower bound: ex. A = 10, K = 3, new_A = 12... try a few more and you will see the pattern is A - A%K + K
  2. Then calculate the following using the above technique:

    • Determine the total number of digits X between [0,B] that are divisible by K
    • Determine the total number of digits Y between [0,A) that are divisible by K
  3. Calculate the number of digits between [A,B] that are divisible by K in constant time by the expression X - Y

Website: https://codility.com/demo/take-sample-test/count_div/

class CountDiv {
    public int solution(int A, int B, int K) {
        int firstDivisble = A%K == 0 ? A : A + (K - A%K);
        int lastDivisible = B%K == 0 ? B : B - B%K; //B/K behaves this way by default.
        return (lastDivisible - firstDivisible)/K + 1;
    }
}

This is my first time explaining an approach like this. Feedback is very much appreciated :)

share improve this answer
 

This is one of the Codility Lesson 3 questions. For this question, the input is guaranteed to be in a valid range. I answered it using Javascript:

function solution(x, y, z) {
    var totalDivisibles =  Math.floor(y / z),
        excludeDivisibles = Math.floor((x - 1) / z),
        divisiblesInArray = totalDivisibles - excludeDivisibles;
   return divisiblesInArray;
}

https://codility.com/demo/results/demoQX3MJC-8AP/

(I actually wanted to ask about some of the other comments on this page but I don't have enough rep points yet).

share improve this answer
 

Divide y-x by z, rounding down. Add one if y%z < x%z or if x%z == 0.

No mathematical proof, unless someone cares to provide one, but test cases, in Perl:

#!perl
use strict;
use warnings;
use Test::More;

sub multiples_in_range {
  my ($x, $y, $z) = @_;
  return 0 if $x > $y;
  my $ret = int( ($y - $x) / $z);
  $ret++ if $y%$z < $x%$z or $x%$z == 0;
  return $ret;
}   

for my $z (2 .. 10) {
  for my $x (0 .. 2*$z) {
    for my $y (0 .. 4*$z) {
      is multiples_in_range($x, $y, $z),
         scalar(grep { $_ % $z == 0 } $x..$y),
         "[$x..$y] mod $z";
    }
  }
}

done_testing;

Output:

$ prove divrange.pl 
divrange.pl .. ok      
All tests successful.
Files=1, Tests=3405,  0 wallclock secs ( 0.20 usr  0.02 sys +  0.26 cusr  0.01 csys =  0.49 CPU)
Result: PASS
share improve this answer
 
1 
Seems correct (and would be the best answer), but you'll need to convince me you're not off-by-one ;-) –  Jan Dvorak  May 5 '13 at 6:33
 
yes.Not off-by-one is the most difficult part of this question... –  Bin Chen  May 5 '13 at 6:36
 
@JanDvorak I don't think I'm up to proving it at 2:30 AM, but it seems to work quite well (after my edit). –  hobbs  May 5 '13 at 6:37
 
@hobbs throw in your test cases, then :-) (and a disclaimer) –  Jan Dvorak  May 5 '13 at 6:37 
1 
Ungh. Dollars everywhere :-) –  Jan Dvorak  May 5 '13 at 6:47

Here is my short and simple solution in C++ which got 100/100 on codility. :) Runs in O(1) time. I hope its not difficult to understand.

int solution(int A, int B, int K) {
    // write your code in C++11
    int cnt=0;
    if( A%K==0 or B%K==0)
        cnt++;
    if(A>=K)
        cnt+= (B - A)/K;
    else
        cnt+=B/K;

    return cnt;
}

What is wrong with my algorithm for finding how many positive integers are divisible by a number d in range [x,y]?

I have been solving basic counting problems from Kenneth Rosen's Discrete Mathematics textbook (6th edition). These come from section 5-1 (the basics of counting), pages 344 - 347. 

This question is not specifically about finding an answer to a problem or being given the correct equation, but whether my reasoning is sound. Therefore I would find it hard to argue this is a duplicate of seemingly similar questions like this one or this one

The problems I have been dealing with come of the form How many positive integers in range [x,y] are divisible by d? All additional questions are based on the composition of the information learned in these, e.g. how many positive integers in range [x,y] are divisible by d or e?

To answer the simple question I wrote this "equation/algorithm," which takes as input an inclusive range of positive integers  [x,y] xy and a positive integer  d d, and returns  n n, the total number of positive integers in range  [x,y] xy which are divisible by  d d

(1)  n=ydxd nydxd

The idea is that in order to count how many positive integers are divisible by  d d from  [1,m] 1m, we simply calculate  md md, because every  dth dth positive integer must be divisible by  d d. However, this does not work when given a range  [x,y] xy where  x1 x1 or when  x>1 x1. So we need to subtract the extra integers we counted, which is  xd xd, i.e. the number of positive integers divisible by  d d from  [1,x] 1x

For a sanity check, I also wrote a brute force algorithm that does a linear search over every positive integer in the range  [x,y] xy and counts it if  x mod d==0 x mod d0. It also can list out the integers it picked, in case I am feeling really paranoid. 

With (1) I've been getting the correct answers except on this problem/input: How many positive integers between 100 and 999 inclusive are odd? My solution was to calculate how many are even, and subtract this from the total number of positive integers in range  [100,999] 100999. To find the evens I simply use the algorithm in (1):

99921002=49950=449 9992100249950449

But this answer is wrong, since there actually  450 450 even numbers in range  [100,999] 100999 by the brute force algorithm. (1) is somehow counting off by 1. My question is, why is (1) failing for this input of  (2,[100,999]) 2100999 but so far it's worked on every other input? What do I need to do to fix (1) so it produces the correct answer for this case? Perhaps I'm actually over counting because  x x should actually be  x1 x1?

(1')  n=ydx1d nydx1d

(1') returns the correct answer for this specific input now, but I am not sure if it will break my other solutions. 

share cite improve this question
 

3 Answers

up vote 1 down vote accepted

After computing the number of positive multiples of  d d less than or equal to  y, y you correctly want to subtract the multiples that are not actually in the range  [x,y]. xy Those are the multiples that are less than  x. x When  x x is divisible by  d, d then  xd xd counts all multiples of  d d up to and including  x x itself. So as you surmised, you want to subtract  x1d x1d instead. This is true for any divisor, not just  d=2. d2.

share cite improve this answer
 
 
You have identified and explained the problem nicely. –  Ross Millikan  Sep 14 '14 at 2:38

another counterexample is [13,6] and 2. the formula seems to be off by 1 if d exactly divides x or (x and y) because then the # of integers in the range [a, b] = b - a + 1. 

share cite improve this answer
 

Suppose you have

(k1)d<xkd<(k+1)d<<(k+n)dy<(k+n+1)d. k1dxkdk1dkndykn1d
Then, you always have  yd=k+n ydkn is  k+n kn. On the other hand, if  x x is divisible by  d d, then  xd=k xdk, whereas if  x x isn't divisible by  d d, then  xd=k1 xdk1. To rectify this, instead use  xd xd which always returns  k k. Your solution is then
n+1=(n+k)k+1=ydxd+1. n1nkk1ydxd1


p.s.

(k1)d<xkd(k1)dx1<kdx1d=k1 k1dxkdk1dx1kdx1dk1
so that
n+1=(n+k)(k1)=ydx1d. n1nkk1ydx1d
The formulas in blue and red produce the same answer.

share cite improve this answer
In the jungle, there is a lake with infinite lily pads on it. The lily pads are numbered with non-negative integers 0,1,2,3,… . The lily pads with numbers between l and r inclusive are called suitable, while all other lily pads are not suitable for the frogs to sit on. Currently, a single frog is sitting on each suitable lily pad. Ostad is watching the lake and wants to reorder the frogs. To do so, Ostad can pick a positive integer x and announce it to the frogs. After hearing the number, the frog sitting on the i -th lily pad will jump to the (i⊕x) -th one, where ⊕ denotes the bitwise XOR operation. Ostad likes the frogs, and therefore he wants to pick the number x in such a way that all frogs stay within the range of suitable lily pads. Help Ostad by counting how many different numbers x Ostad can choose such that no frog jumps outside the suitable segment of the lily pads. Input Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤105 ). The description of the test cases follows. For each test case, there is a single line containing two integers l and r (1≤l≤r≤1015 ). Output For each test case, output a single integer denoting the number of valid values for x . Example InputCopy 5 1 2 3 3 2 4 4 7 24189255811072 59373627899903 OutputCopy 1 0 0 3 2199023255551 Note In the first test case, x=3 is the only number that Ostad can choose, as 1⊕3=2 and 2⊕3=1 , which are within the range [1,2] . There are no valid choices for Ostad in the second and third test cases. For the second case, since we require x>0 , the only frog that we have will leave the range. Similarly, in the third case, no valid x exists to keep the frogs within the desired range. In the fourth test case, Ostad can choose 1 , 2 , or 3 .
最新发布
12-21
\documentclass[12pt]{article} \usepackage{amsmath, amssymb} \usepackage{graphicx} \usepackage{geometry} \usepackage{setspace} \usepackage{caption} \usepackage{titlesec} % 页面设置 \geometry{a4paper, margin=1in} \onehalfspacing % 调整章节标题格式 \titleformat{\section}{\large\bfseries}{\thesection}{1em}{} \titleformat{\subsection}{\normalsize\bfseries}{\thesubsection}{1em}{} % 论文信息 \title{Sieve of Eratosthenes} \author{Zhang Hongwei} \date{December 2, 2025} \begin{document} \maketitle \begin{abstract} This paper describes the Sieve of Eratosthenes, an ancient algorithm for identifying all prime numbers up to a given limit $ n $. The method works by iteratively marking the multiples of each prime starting from 2. We outline its procedure, justify key optimizations, analyze time and space complexity, and compare it with modern variants. A flowchart is included to illustrate the execution process. \end{abstract} \section{Introduction} Finding all primes less than or equal to $ n $ is a basic problem in number theory. While checking individual numbers for primality can be done by trial division, generating many primes efficiently requires a different approach. The Sieve of Eratosthenes, attributed to the Greek mathematician Eratosthenes in the 3rd century BCE, provides a simple and effective solution. It avoids expensive divisibility tests by eliminating composite numbers through multiplication: once a number is identified as prime, all of its multiples are marked as non-prime. Given a positive integer $ n $, the algorithm produces all primes $ \leq n $. Its time complexity is $ O(n \log \log n) $, and it uses $ O(n) $ memory. This makes it practical for $ n $ up to several million on modern computers. \section{Basic Idea} A prime number has no divisors other than 1 and itself. The sieve exploits the fact that every composite number must have at least one prime factor not exceeding its square root. Starting with a list of integers from 2 to $ n $, we proceed as follows: \begin{itemize} \item Mark 2 as prime, then mark all multiples of 2 greater than $ 2^2 = 4 $ as composite. \item Move to the next unmarked number (3), mark it as prime, and eliminate multiples starting from $ 3^2 = 9 $. \item Repeat this process for each new prime $ p $ until $ p > \sqrt{n} $. \end{itemize} After completion, all unmarked numbers are prime. \subsection*{Why start from $ p^2 $?} Any multiple of $ p $ less than $ p^2 $, say $ k \cdot p $ where $ k < p $, would have already been marked when processing smaller primes. For example, $ 6 = 2 \times 3 $ is removed during the pass for 2. Thus, there's no need to revisit these values. \subsection*{Why stop at $ \sqrt{n} $?} If a number $ m \leq n $ is composite, it can be written as $ m = a \cdot b $, with $ 1 < a \leq b $. Then: \[ a^2 \leq a \cdot b = m \leq n \quad \Rightarrow \quad a \leq \sqrt{n}. \] So $ m $ must have a prime factor $ \leq \sqrt{n} $. Therefore, scanning beyond $ \sqrt{n} $ is unnecessary. \section{Implementation Steps} Consider $ n = 100 $. We use a boolean array \texttt{prime[0..100]}, initialized to \texttt{true}. Set \texttt{prime[0]} and \texttt{prime[1]} to \texttt{false}. \begin{enumerate} \item Start with $ p = 2 $. Since \texttt{prime[2]} is true, mark $ 4, 6, 8, \dots, 100 $ as false. \item Next, $ p = 3 $ is unmarked. Mark $ 9, 15, 21, \dots $ (odd multiples $ \geq 9 $). \item $ p = 4 $ is already marked; skip. \item $ p = 5 $ is prime. Mark $ 25, 35, 45, \dots $ \item $ p = 7 $: mark $ 49, 77, 91 $ \item $ p = 11 > \sqrt{100} $, so stop. \end{enumerate} All indices $ i \geq 2 $ where \texttt{prime[i] == true} are prime. \begin{figure}[h!] \centering \includegraphics[width=0.7\linewidth]{Flowchart.jpg} \caption{Flowchart of the Sieve of Eratosthenes algorithm} \label{fig:flowchart} \end{figure} Figure~\ref{fig:flowchart} shows the control flow: initialization, loop over $ p $ from 2 to $ \sqrt{n} $, and marking multiples starting at $ p^2 $. \section{Complexity Analysis} \subsection{Time Usage} For each prime $ p \leq \sqrt{n} $, we mark about $ n/p $ elements. Summing over such $ p $: \[ T(n) \approx n \sum_{\substack{p \leq \sqrt{n} \\ p\ \text{prime}}} \frac{1}{p}. \] It is known from number theory that the sum of reciprocals of primes up to $ x $ grows like $ \log \log x $. So: \[ \sum_{p \leq \sqrt{n}} \frac{1}{p} \sim \log \log \sqrt{n} = \log(\tfrac{1}{2}\log n) = \log \log n + \log \tfrac{1}{2} \approx \log \log n. \] Hence, total time is $ O(n \log \log n) $. \subsection{Memory Requirement} The algorithm requires one boolean value per integer from 0 to $ n $, leading to $ O(n) $ space usage. \section{Variants and Practical Considerations} \begin{table}[h!] \centering \caption{Common methods for generating primes} \label{tab:methods} \begin{tabular}{|l|c|c|l|} \hline Method & Time & Space & Remarks \\ \hline Trial division (single number) & $O(\sqrt{n})$ & $O(1)$ & Simple, slow for batches \\ Standard sieve & $O(n \log \log n)$ & $O(n)$ & Good for $ n \leq 10^7 $ \\ Segmented sieve & $O(n \log \log n)$ & $O(\sqrt{n})$ & Reduces memory usage \\ Linear sieve (Euler) & $O(n)$ & $O(n)$ & Faster in theory, more complex \\ \hline \end{tabular} \end{table} In practice, the standard sieve performs well due to good cache behavior and low constant factors. For very large $ n $, segmented versions divide the range into blocks processed separately. The linear sieve improves asymptotic time by ensuring each composite is crossed off exactly once using its smallest prime factor, but the overhead often negates benefits for moderate inputs. \section{Conclusion} The Sieve of Eratosthenes remains a fundamental tool in algorithm design. Its simplicity allows easy implementation and teaching, while its efficiency supports real-world applications in cryptography, number theory, and data processing. Although newer algorithms exist, the original sieve continues to be relevant—especially when clarity and reliability matter more than marginal speed gains. With minor improvements, it scales well within typical computational limits. \section{References} \begin{thebibliography}{9} \bibitem{knuth} Donald E. Knuth. \textit{The Art of Computer Programming, Volume 2: Seminumerical Algorithms}. 3rd Edition, Addison-Wesley, 1997. ISBN: 0-201-89684-2. (See Section 4.5.4 for discussion of prime number sieves.) \bibitem{hardy} G. H. Hardy and E. M. Wright. \textit{An Introduction to the Theory of Numbers}. 6th Edition, Oxford University Press, 2008. ISBN: 978-0-19-921986-5. (Chapter 1 discusses prime numbers and includes historical notes on Eratosthenes.) \bibitem{pomerance} Carl Pomerance. \newblock “A Tale of Two Sieves.” \newblock \textit{Notices of the American Mathematical Society}, vol.~43, no.~12, pp.~1473–1485, December 1996. Available online: \url{https://www.ams.org/journals/notices/199612/199612FullIssue.pdf#page=1473} \bibitem{crandall} Richard Crandall and Carl Pomerance. \textit{Prime Numbers: A Computational Perspective}. 2nd Edition, Springer, 2005. ISBN: 978-0-387-25282-7. (A detailed treatment of sieve methods including Eratosthenes and segmented variants.) \bibitem{eratosthenes-original} Thomas L. Heath (Ed.). \textit{Greek Mathematical Works, Volume II: From Aristarchus to Pappus}. Harvard University Press (Loeb Classical Library), 1941. ISBN: 978-0-674-99396-7. (Contains surviving fragments and references to Eratosthenes’ work in ancient sources.) \end{thebibliography} \end{document} 修改错误 ,并且增加字数在2000字左右
12-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值