Algorithm 以3结尾的数字至少有一个倍数包含所有1
您好,这是Adobe采访中提出的一个问题Algorithm 以3结尾的数字至少有一个倍数包含所有1,algorithm,numbers,Algorithm,Numbers,您好,这是Adobe采访中提出的一个问题 Numbers ending in 3 have at least one multiple having all ones. for eg., 3 and 13 have amultiples like 111 and 111111 respectively. Given such a no. , find the smallest such multiple of that number. The multiple can exceed the
Numbers ending in 3 have at least one multiple having all ones.
for eg., 3 and 13 have amultiples like 111 and 111111 respectively. Given such
a no. , find the smallest such multiple of that number. The multiple can
exceed the range of int, long. You cannot use any complex data structure.
你能为我提供一个有效的解决方案吗现在我得到了答案:)
int count=1,rem=1;
while(rem)
{
雷姆=(雷姆*10+1)%n;计数++;
}
虽然(count--){cout这里有一个尝试,试图比尝试1、11、111、111更有效..这会有回报吗?有没有比一次尝试一个数字更好的更优雅的答案
将数字1、11、111……写成(10^k-1)/9,其中除法是精确的。给定一个10x+3形式的目标数字,我们想找到最小的k解(10^k-1)/9=Y(10x+3),其中Y是整数。寻找10^k=1模9(10x+3)的小解。这是算术模9(10x+3)除外不一定形成一个组-但该算法仍应适用,并可用于搜索稳步增加的k范围,而不是一次搜索一个可能的k值。\35; include
#include <iostream>
using namespace std;
int main() {
int t;
cin>>t;
while(t--){
long long n;
cin>>n;
long long cur = 1;
while(cur%n!=0){
cur = cur*10+1;
}
cout<<cur<<endl;
}
return 0;
}
使用名称空间std;
int main(){
int t;
cin>>t;
而(t--){
长n;
cin>>n;
长电流=1;
而(当前%n!=0){
cur=cur*10+1;
}
cout与输出大小无关的解决方案:
public String ones(int n)
{
int i, m = 1;
String num="1";
for (i = 1; i <= n; i++) {
if (m == 0)
return num;
/* Solution found */
num=num+"1";
m = (10*m + 1) % n;
}
return null; /* No solution */
公共字符串(int n)
{
int i,m=1;
字符串num=“1”;
对于(i=1;i那么你到底需要什么?给出了一个解释性的答案。你可能的重复只是说倍数可能会超过整数范围。@HighPerformanceMark这个问题并不排除整数或长整数-它只是说明一个解决方案可能会超过这样的范围。它排除使用复杂的数据结构。它不排除u使用模运算并观察xmod3
和(x*10+1)之间的关系mod 3
要计算一个表示适当倍数的字符串,而不实际计算这样的倍数…@Aravind yes it is count是倍数中出现的次数1的次数,而循环打印该数字是一个很好的解决方案!你能详细说明一下它是如何使用模运算的吗?我想是的对于工作面试或家庭作业来说,这不是一个好答案。使用Fermat的小定理是可行的。使用long-long
来避免超出int的范围,long
是很糟糕的。您是否试图理解其他解决方案如何不需要数字(很多)大于给定的数字?我确实认为这是实际的解决方案,而不是其他解决方案。但我只是想了解它比尝试1、11111等更有效吗?我们计算的是10^k模A(假设A=9(10x+3))每次迭代,随着k的增加,对吗?如果存储10^k的变量溢出,结果非常大怎么办?这是面试官期望使用一致性属性的最佳方法吗?-谢谢。我只是好奇。所需的算法是mod 9(10x+3)如果溢出,除非你切换到多精度,否则你就不走运了,但这发生在10^k溢出后的某个时间。效率来源于这样一个事实,即婴儿步/大步算法允许你在时间O(sqrt(N))内搜索N个可能性范围
public String ones(int n)
{
int i, m = 1;
String num="1";
for (i = 1; i <= n; i++) {
if (m == 0)
return num;
/* Solution found */
num=num+"1";
m = (10*m + 1) % n;
}
return null; /* No solution */