Cses problem 2: missing number

I have been trying to solve this problem in rust. I am able solve for the small inputs for the problem but I am unable to do for bigger inputs. I don't know how I can take so many inputs. I am sharing the link to the Problem: LINK. I am also sharing my code here:
use std::io;

fn main() {
let mut n: String = String::new();
match io::stdin().read_line(&mut n) {
Err(error) => eprintln!("Error: {}", error),
Ok(_) => (),

    let n: u32 = n.trim().parse().unwrap();
    // println!("{}", n);

    // let mut num: Vec<u32> = vec![0; n];
    let mut i: String = String::new();
    match io::stdin().read_line(&mut i) {
        Err(error) => eprintln!("Error: {}", error),
        Ok(_) => (),
    let mut sum: u128 = 0;

    let p: &str = &i;
    for s in p.split(' ').collect::<Vec<&str>>().into_iter() {
        let s1: u128 = s.trim().parse().unwrap();
        // num[(s1 as usize) - 1] = s1;
        sum += s1;
        // println!(" {} {}", s1, sum);

    let mut s1: u128 = (n * (n + 1)) as u128;
    s1 /= 2;
    println!("{:?}", s1 - sum);
    // println!("{:?}", num);

Please help with it.

Got it, it’s an overflow. You first multiply n*(n+1) with u32s and then cast the result to u128.

The code can be simplified. Here's a rough sketch: (I used u64 since 2e5 * (2e5 + 1) is just a bit over 2^32)

use std::io;

fn main() {
    let n: u64 = read_line().trim().parse().unwrap();
    let sum: u64 = read_line()
        .map(|s| s.parse::<u64>().unwrap())

    let missing_number = n * (n + 1) / 2 - sum;
    println!("{}", missing_number);

fn read_line() -> String {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();

Thank for your help I miss the fact that multiplication would overflow u32!

Thank for your simplified solution. I am currently learning rust through solving problems so I didn't think about using these feature.

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.