假设有两个整数 x 和 N。
我正在尝试确定如何构造一个算法,该算法将返回值 x 重复 N 次的整数。
因此,如果 x 为 9 且 N 为 4,则等式将返回 9999。
如果 x 为 9 且 N 为 5,则等式将返回 99999。(令人作呕)
我希望这在 SO 上不是完全荒谬或不合适的。:)
这对我有用: (10^N-1)/9*x
请注意,x 是一个整数,在 base-10 系统中它不必是 1 位数字。如果 N = 3 且 x = 12 会怎样?那么答案应该是 121212。
这是解决方案:我们需要以p
10 为底的系统中数字 x 的长度。让p = floor(lg(x)+1)
. 我们正在搜索的数字是x + x*10^p + x*10^2p + ... + x*10^(N-1)p
。那就是x * (10^(pN) - 1) / (10^p - 1)
。
这似乎更像是一个编程问题,因为解决方案在很大程度上依赖于以 10 为底的数字系统。执行此操作的算法只是一个简单的 N 循环,它将前一个数字相乘并添加一个 x。
int foo(int x, int N) {
int result = 0;
for(i=0; i<N; i++) {
result *= 10;
result += x;
}
return result;
}
在 python 中,这非常简单:
def repeat(x, N):
return int(str(x) * N)
伪代码:
Procedure Construct takes x:integer N:integer
begin
take a variable Result and initialize with 0;
For N times Do
begin
Result <- Result * 10
Result <- Result + x
end
end
一个 C++ 示例:
int main()
{
const int x = 9, N = 5;
int Result = 0;
for(int i = 0; i < N; ++i)
{
Result*=10;
Result+=x;
}
//use result here
}
只是有点不同,我用这个递归函数做了一个 JavaScript 小提琴:
function repeating(x, n){
return (n) ? (x * Math.pow(10,n-1)) + repeating(x, n-1) : 0;
};
小提琴:http: //jsfiddle.net/SZKeb/2/
它只是从 N 向后工作,所以基本上将计算为9000 + 900 + 90 + 9 + 0 = 9999
听起来您更像是在尝试构建一串重复数字,而不是在做实际的数学运算。为什么不执行以下(C#)?
using System;
using System.Text;
public int CreateInt(int x, int N)
{
StringBuilder createdString = new StringBuilder();
int createdInt;
for (int i = 0; i < N; i++)
createdString.Append(x.ToString());
if (!int.TryParse(createdString.ToString(), out createdInt))
throw new Exception(string.Format("Value x ({0}) repeated N ({1}) times makes {2}. This is not a valid integer.", x, N, createdString));
return createdInt;
}
int createdInt1 = CreateInt(7, 5); // output: 77777
int createdInt2 = CreateInt(14, 4); // output: 14141414
int createdInt3 = CreateInt(1, 20); // output: throws exception "Value x (1) repeated N (20) times makes 11111111111111111111. This is not a valid integer."
此示例显示了您需要注意的几件事:
伪代码跟随。本质是你要数到 n 并且每次数你都会打印出你的 x
for(int i=1; i <=x ; i++)
{
system.print("n");
}
x*(10^(floor(log(x)-1)*N))/(10^(floor(log(x)-1)*N))