Vikaton
Vikaton

Reputation: 2407

Hidden Logic errors in code?

My goal here is to find the first triangular number with 500 divisors, from Project Euler. This is what I have so far:

use std::num::Float;

fn main() {
    let mut num = vec!(1 , 3 , 6 , 10);
    let mut a = 0us;
    let mut fac = vec![];
    for _ in (0us..1000000us) {
        let x =
            num[num.len() - 1] - num[num.len() - 2] + 1 +
                num[num.len() -
                        1]; //extremely clever way of listing triangle numbers(not to be cocky :))
        num.push(x);
    }
    println!("{:?}" , num);
    println!("Calculating...");
    let mut _i = 1is;
    for _ in (0us..num.len() as usize) {
        for _ in (1us..(num[a] as f64).sqrt() as usize) {                                        //Logic Error
            if num[a] % _i == 0 { fac.push(_i); }
            //print!("{},\n" , res.len()); }
            _i += 1;
        }
        fac.push(num[a] as isize,);
        if fac.len() >= 10 {println!("Length: {}\nVector: {:?}\nValue: {}\n\nYOU GOT THE ANSWER! WOOT! \x07", fac.len(), fac, num[a]); break;}
        _i = 1;
        fac = vec![];
        a+=1
    }
}

but this prints '864864000' as the value which isn't correct, which doesn't make sense to me, I have tried 499(since the vector doesn't include the number itself) and 501 and 502 and I get the same number.

P.S: please don't try to make my code look cleaner or propose the closed form formula, as I'm trying to do this with my bare brain, which now needs a bit of help :)

Upvotes: 0

Views: 91

Answers (2)

David Brown
David Brown

Reputation: 247

When computing divisors, you cannot stop at the square root of the number. At best, you could stop at n/i where n is the number you are counting the divisors of, and i is the lowest divisor greater than 1.

For example, when counting the divisors of 12, you would only try dividing by 1, 2 and 3, which would give you a divisor count of 4 instead of six, since it misses that 4 and 6. This results in you finding many fewer divisors than the numbers actually have.

Possibly this comes from the vector holding the divisors being called fac which suggests that they are factors instead of divisors.

Upvotes: 0

Mutabah
Mutabah

Reputation: 111

Most likely, your errors are coming from converting a very large integer to f32 and then comparing (which loses accuracy)

Upvotes: 3

Related Questions