-2

How can we get n times 1 by using n. you can use only arithmetic operations not string functions. like


  • if n equals 1 output equals 1
  • if n equals 2 output equals 11
  • if n equals 3 output equals 111
  • if n equals 4 output equals 1111
  • any loop is not allowed
  • 5
    Please update your question with the code you have tried. – quamrana May 18 '20 at 13:38
  • `int("1" * n)`? – jonrsharpe May 18 '20 at 13:38
  • 1
    You can do it recursively. – ywbaek May 18 '20 at 13:39
  • 2
    Welcome to SO. Be aware that StackOverflow isn't a website where you give "problems" to the community to solve for you. Instead, you are expected to solve it yourself – and if and when you get stuck having **a specific programming problem**, then it's a good time to ask it here. Have a look at [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask). – Ivo Mori May 18 '20 at 13:52
  • Hint - You should use the power operator, some subtraction, and a division by 9. Now you find the order and missing operands of these operators. – Amitai Irron May 18 '20 at 14:03

2 Answers2

0

Try this:

def func(n): 
    if n==1: 
        return 1 
    return 10**n - 8*func(n-1)*10 - 9 

test:

In [49]: func(10)                                                                                                                                                                                                                                                                                                              
Out[49]: 1111111111

In [50]: func(3)                                                                                                                                                                                                                                                                                                               
Out[50]: 111

In [51]: func(4)                                                                                                                                                                                                                                                                                                               
Out[51]: 1111
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

You can do it this way. It is a recursive function:

def get_ones(n):
    if (n == 0):
        return 0
    elif (n == 1):
        return 1

    return 10**(n-1) + get_ones(n-1)

print(get_ones(5))

The idea is that 111 = 1*(10^0) + 1*(10^1) + 1*(10^2)

Anouar
  • 2,050
  • 1
  • 15
  • 25