How to increase speed for my code?

I'm doing cses-permutation
My code:

use std::io;

fn main() {
    let num: i64 = input().trim().parse().unwrap();
    if num == 1 {
        println!("{}", 1);
    } else if num <= 3 {
        println!("NO SOLUTION")
    } else {
        for i in (1i64..=num).step_by(2) {
            print!("{} ", i);
        }
        for i in (5i64..=num).step_by(2) {
            print!("{} ", i);
        }
    }
}

fn input() -> String {
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("Fail when readline");
    input
}

After optimization:

use std::fmt::Write;
use std::io;

fn main() {
    let num: i64 = input().trim().parse().unwrap();
    if num == 1 {
        println!("{}", 1);
    } else if num <= 3 {
        println!("NO SOLUTION")
    } else {
        let mut string = String::new();
        for i in (2i64..=num).step_by(2) {
            write!(string, "{} ", i).unwrap();
        }
        for i in (1i64..=num).step_by(2) {
            write!(string, "{} ", i).unwrap();
        }
        println!("{}", string);
    }
}

fn input() -> String {
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("Fail when readline");
    input
}

The 2nd code faster than 2 times.

How use write! marco is faster than use print! ?

How to make it better and faster ?

Thanks you!!!

It only locks stdout once as there is a single write to stdout. Every time you run print!() you lock stdout, which is relatively slow. You can take std::io::stdout().lock() and call write!() on the resulting locked stdout as alternative.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.