How to build a repeating equation?

Suppose two integers x and N.

I am trying to figure out how to build an algorithm that returns an integer x repeating N times.

So, if x is 9 and N is 4, the equation will return 9999.
And if x is 9 and N is 5, the equation will return 99999. (ad nauseam)

Hope this is not entirely absurd or inappropriate on SO. :)

+3
source share
8 answers

Note that x is an integer, and it should not be a 1-digit number in the base-10 system. What if N = 3 and x = 12? Then the answer should be 121212.

: p x base-10. p = floor(lg(x)+1). , , x + x*10^p + x*10^2p + ... + x*10^(N-1)p. x * (10^(pN) - 1) / (10^p - 1).

+4

: (10 ^ N-1)/9 * x

+10

, -10. N, x.

int foo(int x, int N) {
  int result = 0;
  for(i=0; i<N; i++) {
    result *= 10;
    result += x;
  }
  return result;
}
+2

:

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

++:

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
}
+1

, JavaScript :

function repeating(x, n){
    return (n) ? (x * Math.pow(10,n-1)) + repeating(x, n-1) : 0;
};

Fiddle: http://jsfiddle.net/SZKeb/2/

N, 9000 + 900 + 90 + 9 + 0 = 9999

+1

python :

def repeat(x, N):
    return int(str(x) * N)
+1

. , n, , , x

for(int i=1; i <=x ; i++)
{
 system.print("n");
}
0

, , . (#)?

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) ?
0

Source: https://habr.com/ru/post/1769626/


All Articles