📌  相关文章
📜  给定数字n,请计算集合{1,2,3,… n}中3和/或5的所有倍数

📅  最后修改于: 2021-04-27 18:07:30             🧑  作者: Mango

给定数字n,请计算从1到n的数字集中3和/或5的所有倍数。

例子:

Input: n = 6
Output: 3
There are three multiples of 3 and/or 5 in {1, 2, 3, 4, 5, 6}

Input: n = 16
Output: 7
There are two multiples of 7 and/or 5 in {1, 2, .. 16}
The multiples are 3, 5, 6, 9, 10, 12, 15

强烈建议最小化您的浏览器,然后自己尝试。

n / 3的值给我们3的倍数,n / 5的值给我们5的倍数。但是重要的一点是可能存在一些常见的倍数,它们都是3和5的倍数。我们可以通过使用n / 15获得这样的倍数。以下是查找倍数计数的程序。

C++
// C++ program to find count of multiples of 3 and 5 in {1, 2, 3, ..n}
#include 
using namespace std;
  
unsigned countOfMultiples(unsigned n)
{
   // Add multiples of 3 and 5.  Since common multples are
   // counted twice in n/3 + n/15, subtract common multiples
   return (n/3 + n/5 - n/15);
}
  
// Driver program to test above function
int main()
{
   cout << countOfMultiples(6) << endl;
   cout << countOfMultiples(16) << endl;
   return 0;
}


Java
// Java program to find count of multiples
// of 3 and 5 in {1, 2, 3, ..n}
import java .io.*;
class GFG {
      
    static long countOfMultiples(long n)
    {
          
        // Add multiples of 3 and 5. 
        // Since common multples are
        // counted twice in n/3 + n/15, 
        // subtract common multiples
        return (n/3 + n/5 - n/15);
    }
      
    // Driver Code
    static public void main (String[] args)
    {
        System.out.println(countOfMultiples(6));
        System.out.println(countOfMultiples(16));
    }
}
  
// This code is contributed by anuj_67.


Python3
# python program to find count
# of multiples of 3 and 5 in 
# {1, 2, 3, ..n}
  
def countOfMultiples(n):
    # Add multiples of 3 and 5.
    # Since common multples are
    # counted twice in n/3 + n/15,
    # subtract common multiples
    return (int(n/3) + int(n/5) - int(n/15));
  
  
# Driver program to test
# above function
print(countOfMultiples(6))
print(countOfMultiples(16))
  
# This code is contributed by Sam007.


C#
// C# program to find count of multiples
// of 3 and 5 in {1, 2, 3, ..n}
using System;
  
public class GFG {
      
    static uint countOfMultiples(uint n)
    {
        // Add multiples of 3 and 5. 
        // Since common multples are
        // counted twice in n/3 + n/15, 
        // subtract common multiples
        return (n/3 + n/5 - n/15);
    }
      
    // Driver program to test above
    // function
    static public void Main ()
    {
        Console.WriteLine(countOfMultiples(6));
          
        Console.WriteLine(countOfMultiples(16)) ;
    }
}
  
// This code is contributed by anuj_67.


PHP


输出:

3
7