Total Pageviews

Wednesday, January 20, 2021

Project Euler - Rust problem 12

 On the Project Euler site, which I highly recommend, they don't want anyone sharing answers over 100.  I'm cool with that.  Once I get there, I'll share other things.  I'm getting more comfortable with Rust so we'll see where that goes.


Problem 12 - Project Euler

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

Let us list the factors of the first seven triangle numbers:

 1: 1

 3: 1,2,3

 6: 1,2,3,6

10: 1,2,5,10

15: 1,3,5,15

21: 1,3,7,21

28: 1,2,4,7,14,28

We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?


There's a few ways to approach this.  I chose to go into this brute force style.  


[dependencies]
divisors = "0.2.1"


Here's my single dependency and the code.


use std::time::{Instant};

fn main() {
    let start_time = Instant::now();
    let mut final_num: u32 = 0;
    let mut divisor_count: u32 = 0;
    let mut count: u32 = 1;

    while divisor_count < 498{
        let triangle = get_tri(count);
        let divisors = divisors::get_divisors(triangle);
        divisor_count = divisors.len() as u32;
        final_num = triangle;
        count += 1;
    }
println!("time = {:?}, final number = {:?}", start_time.elapsed(), final_num);
}


fn get_tri(x: u32) -> u32 {
    let mut count = x;
    let mut sum = 0;
    while count > 0{
        sum += count;
        count -= 1;
    }
    sum
}

Here we go. Declaring the final_num, the divisor count, and the count.  Then the loop. While the divisor count is less than 498 the loop will run.

Why 498?  I used 498 as the threshold because it would return on divisor length being 499 and this particular crate doesn't count 1 as a divisor where most of the problems do consider it. So I always have to take that into consideration when I use this crate.

In the loop, we define the triangle based on the current count.  That count is incremented by 1 at the end of the loop.  We get the number of divisors for the triangle. Assign final number to the triangle and increment the count.

Once it reaches 499, it breaks the while and prints the answer.  

I included the time thing just for fun.  I did go back and change the let triangle = get_tri(count) to final_num = get_tri(count).  It works. It's not as efficient as some of the other answers in other languages but it does get the job done. 1.5 seconds.


No comments: