2つの整数xとNを想定します。
N回繰り返される値xの整数を返すアルゴリズムを構築する方法を決定しようとしています。
したがって、xが9でNが4の場合、方程式は9999を返し
ます。xが9でNが5の場合、方程式は99999を返します。
これが完全に馬鹿げていたり、SOで場違いになったりしないことを願っています。:)
これは私のために働きます:(10 ^ N-1)/ 9 * x
xは整数であり、基数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の記数法に大きく依存しているため、これはプログラミングの問題のように思われます。これを行うためのアルゴリズムは、前の数を乗算してxを追加するN上の単純なループになります。
int foo(int x, int N) {
int result = 0;
for(i=0; i<N; i++) {
result *= 10;
result += x;
}
return result;
}
擬似コード:
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
Pythonでは、これは非常に簡単です。
def repeat(x, N):
return int(str(x) * N)
従うべき擬似コード。これの本質は、nまでカウントすることであり、カウントするたびにxを出力します。
for(int i=1; i <=x ; i++)
{
system.print("n");
}
実際の数学を行うよりも、繰り返し数の文字列を作成しようとしているように聞こえます。次の(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."
このサンプルは、注意したいいくつかのことを示しています。
x*(10^(floor(log(x)-1)*N))/(10^(floor(log(x)-1)*N))