Rust: recursion, efficiency and substitution, overflow _rust

Source: Internet
Author: User

or the Codewars:

Given: U (0) = 1, u (1) = 2,
has a relationship: 6u (n) *u (n+1) -5u (n) *u (n+2) +u (n+1) *u (n+2) = 0 Calculates any n >= 0 that satisfies the condition.

#Examples

FCT (n) returns UN:FCT (-> 131072, FCT ()-> 2097152

Apparently, the recursive

First, recursive

fn FCN (n:i32)-> i64 {
    //Your code
    match n {
        0 => return 1i64,
        1 => return 2i64,
        _ => { C8/>return 6i64 * FCN (n-1) * FCN (n-2)/(5i64 * FCN (n-2)-FCN (n-1));}}

After testing, pass the test. However, when committed, the runtime timed out and failed to pass. Can only be dropped, the conversion method.

Second, the new algorithm

fn FCN (n:i32)-> i64 {
    //Your code let
    mut hp:hashmap<i32, i64> = Hashmap::new ();
    Hp.insert (0I32, 1i64);
    Hp.insert (1I32, 2i64);
    Hp.insert (2I32, 4i64);
    For I in 3. (n + 1) {Let
        i_1 = Hp.get (& (I-1)). Unwrap (). Clone ();
        Let i_2 = Hp.get (& (I-2)). Unwrap (). Clone ();
        Let temp = 5i64 * i_2-i_1;
        println! ("i_1:{}, i_2:{} temp:{}", I_1, I_2, temp);
        Let val = 6i64 * i_2 * I_1/TEMP;
        Hp.insert (I, Val);
    }
    * (Hp.get (&n). Unwrap ())
}

But the new question comes, when n is big, you look at:

Let val = 6i64 * i_2 * I_1/TEMP;

can cause i64 overflow. How does this work?

Iii. Inductive method of mathematics

In fact, if you try to calculate, you will find that these numbers are regular:

fn FCN (n:i32)-> i64 {
    2i64.pow (n as u32)
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.