📌  相关文章
📜  打印给定数字的所有可被 5 或 7 整除的数字

📅  最后修改于: 2022-05-13 01:54:42.965000             🧑  作者: Mango

打印给定数字的所有可被 5 或 7 整除的数字

给定整数 N,任务是打印所有小于 N 的数字,这些数字可以被 5 或 7 整除。

例子 :

Input : 20
Output : 5 7 10 14 15 20 

Input: 50
Output: 5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50

方法:例如,让我们以 N = 20 作为限制,那么程序应该打印所有小于 20 且可以被 5 或 7 整除的数字。为此,将 0 到 N 中的每个数字除以 5 和 7 并检查它们余。如果两种情况下的余数均为 0,则只需打印该数字。

下面是实现:

C++
// C++ program to print all the numbers
// divisible by 5 or 7 for a given number
# include
using namespace std;
 
// Result generator with N
int NumGen(int n)
{
 
    // Iterate from 0 to N
    for(int j = 1; j < n + 1; j++)
    {
 
        // Short-circuit operator is used
        if (j % 5 == 0 || j % 7 == 0)
            cout << j << " ";
    }
    return n;
}
 
// Driver code
int main()
{
    // Input goes here
    int N = 50;
     
    // Iterating over generator function
    NumGen(N);
     
    return 0;
}
 
// This code is contributed by Code_Mech


Java
// Java program to print all the numbers
// divisible by 5 or 7 for a given number
import java.util.*;
 
class GFG{
     
// Result generator with N
static int NumGen(int n)
{
 
    // Iterate from 0 to N
    for(int j = 1; j < n + 1; j++)
    {
 
       // Short-circuit operator is used
       if (j % 5 == 0 || j % 7 == 0)
           System.out.print(j + " ");
    }
    return n;
}
 
// Driver code
public static void main(String args[])
{
    // Input goes here
    int N = 50;
     
    // Iterating over generator function
    NumGen(N);
}
}
 
// This code is contributed by AbhiThakur


Python3
# Python3 program to print all the numbers
# divisible by 5 or 7 for a given number
 
# Result generator with N
def NumGen(n):
     
    # iterate from 0 to N
    for j in range(1, n+1):
 
        # Short-circuit operator is used
        if j % 5 == 0 or j % 7 == 0:
            yield j
 
# Driver code
if __name__ == "__main__":
       
    # input goes here
    N = 50
 
    # Iterating over generator function
    for j in NumGen(N):
        print(j, end = " ")


C#
// C# program to print all the numbers
// divisible by 5 or 7 for a given number
using System;
 
class GFG{
     
// Result generator with N
static int NumGen(int n)
{
 
    // Iterate from 0 to N
    for(int j = 1; j < n + 1; j++)
    {
 
       // Short-circuit operator is used
       if (j % 5 == 0 || j % 7 == 0)
           Console.Write(j + " ");
    }
    return n;
}
 
// Driver code
public static void Main()
{
 
    // Input goes here
    int N = 50;
     
    // Iterating over generator
    // function
    NumGen(N);
}
}
 
// This code is contributed by Code_Mech


Javascript


输出:

5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50 

时间复杂度: O(N)

辅助空间: O(1)