检查一个数字的所有前缀是否可以被剩余的位数整除
给定一个数N,任务是检查对于i ( 0 <= i <= len )的每个值,一个数的前i位是否可以被(len – i + 1)整除,其中len是N中的位数。如果发现是真的,则打印“是” 。否则,打印“否”。
例子:
Input: N = 52248.
Output: Yes
Explanation:
- 5 is divisible by 5
- 52 is divisible by 4
- 522 is divisible by 3
- 5224 is divisible by 2
- 52248 is divisible by 1
Input: N = 59268
Output : No
方法:想法是遍历给定数字的所有前缀,对于每个前缀,检查它是否满足条件。
请按照以下步骤解决问题:
- 初始化一个变量,比如i为1,以保持(len – i + 1 ) 的值。
- 在n大于0 时迭代。
- 如果N不能被i 整除,则返回false。
- 否则,将N除以10并将i的值增加1 。
- 最后,返回真。
下面是上述方法的实现。
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if all prefixes
// of a number is divisible by
// remaining count of digits or not
bool prefixDivisble(int n)
{
int i = 1;
while (n > 0) {
// Traverse and check divisibility
// for each updated number
if (n % i != 0)
return false;
// Update the original number
n = n / 10;
i++;
}
return true;
}
// Driver Code
int main()
{
// Given Input
int n = 52248;
// Function Call
if (prefixDivisble(n))
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG{
// Function to check if all prefixes
// of a number is divisible by
// remaining count of digits or not
public static boolean prefixDivisble(int n)
{
int i = 1;
while (n > 0)
{
// Traverse and check divisibility
// for each updated number
if (n % i != 0)
return false;
// Update the original number
n = n / 10;
i++;
}
return true;
}
// Driver Code
public static void main (String[] args)
{
// Given Input
int n = 52248;
// Function Call
if (prefixDivisble(n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by lokeshpotta20.
Python3
# Python3 program for the above approach
# Function to check if all prefixes of
# a number is divisible by remaining count
# of digits or not
def prefixDivisble(n):
i = 1
while n > 0:
# Traverse and check divisibility
# for each updated number
if n % i != 0:
return False
# Update the original number
n = n // 10
i += 1
return True
# Driver Code
# Given Input
n = 52248
# Function Call
if (prefixDivisble(n)):
print("Yes")
else:
print("No")
# This code is contributed by abhivick07
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to check if all prefixes
// of a number is divisible by
// remaining count of digits or not
static bool prefixDivisble(int n)
{
int i = 1;
while (n > 0)
{
// Traverse and check divisibility
// for each updated number
if (n % i != 0)
return false;
// Update the original number
n = n / 10;
i++;
}
return true;
}
// Driver Code
public static void Main()
{
// Given Input
int n = 52248;
// Function Call
if (prefixDivisble(n))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by ipg2016107
Javascript
输出
Yes
时间复杂度: O(len),其中 len 是N中的位数。
辅助空间: O(1)