When we use python, we can print same string multiple times by using print("1"*n). This helps to reduce the execution time. If we have a method to do that in C, it would be helpful.
Expected result is the time complexity of O(n).
On
Yes you can use recursion to print "1" n times.
#include <stdio.h>
void printOne(int n) {
// Base case: if n is 0, stop recursion
if (n == 0)
return;
// Print 1
printf("1 ");
// Recursively call printOne with n-1
printOne(n - 1);
}
int main() {
int n;
// Get input from the user
printf("Enter the number of times to print 1: ");
scanf("%d", &n);
// Call the recursive function
printOne(n);
return 0;
}
On
It seems in this expression "1"*n there is built a string with n characters that is outputted. In C you have to build such a string yourself by using for example a variable length array. Something like the following:
#include <string.h>
#include <stdio.h>
void print_n( int n )
{
if ( n > 0 )
{
char s[n];
memset(s, '1', n );
printf( "%.*s\n", n, s );
}
}
Python is an interpreted language.
When you write something like:
The Python interpreter performs a loop internally.
It is more efficient in Python because the interpreter is usually written in a compiled language like C (or C++) and so the loop is more efficient when done internally.
But since C itself is a compiled language writting a simple loop (which will be done in O(n) as you requested), is the most efficient thing you can do. This loop can be either "manually" written or via some library function like
memsetwhich is implemented with a loop.Note that such a loop can be replaced with a recursion, but this is not expected to improve performance (recursion is usually less efficient than a simple loop).
The most "expensive" operation in this case is actually the I/O which might be buffered.
So the best you can do might be to build the final string (with a loop) into a buffer, and then use one
printfstatement to dump it the console.As usual with matters of performance, you should profile it to check.
Note: The answer above assumes that
nisn't known in advance, and can be arbitrarily large.I used this assumption because:
(1) The python statement used as a reference hints to that.
(2) The OP mentioned O(n) complexity which is meaningful only when
nis relatively large.