#include<iostream>
#include<cstdlib>
usingnamespace std;
int main(){
unsigned a, number, divisor, factors, term=0;
while(1){
a = 0;
number = 0;
while(a <= term){
number += a;
a += 1;
} //gets next triangle number
divisor = 1;
factors = 0;
while(divisor <= number){
if(number % divisor == 0){
factors += 1; //gets number of factors
if(factors > 500){
cout << number << endl; //displays number if it has more than 500 factors
system("pause>nul");
return 0;
}
}
divisor += 1;
}
term += 1;
}
return 0;
}
It takes ~10s for the first triangle number with 320 factors, but no higher.
I have left it for at least 1 hour with no output.
Please help me work out why, but ideally without just solving the whole problem.
Well... if a number p is evenly divisible by q, then it is also divisible by p/q.
So there's no need to test further than sqrt(p). With that change, the program gives me the result in less than a second.
Yeah, that's what I meant. When number is a square number, factors should be one less
(because of p/q=q for q=sqrt(p)), but at least for this particular problem, it doesn't change the answer.
I don't get this code
forgive me if i am wrong , i am a newbie .
1 2 3 4 5 6 7 8 9 10
while(1) //infinite loop?
{
a = 0;
number = 0;
while(a <= term)/* first loop[ 0<=0 , number += 0, a+=1 ] 2nd loop [ a (1) <= term(0) == false ; loop breaks] */
{
number += a;
a += 1;
}
the 'while' loop at the top keeps executing and nothing will ever stop it. You need a flag/counter? to change it when you have your required result other wise your other code will never execute.
you're also initializing 'a' to 0 both times first when you're declaring your variables and second time in the while loop .
Also 'factor' is already initialized to zero at line 7 , no need to have it again in 19.
I am in a rush so sorry if i can't help you out completely with your program.
best of luck.
the 'while' loop at the top keeps executing and nothing will ever stop it.
There's something that will: the return in line 28.
Also 'factor' is already initialized to zero at line 7 , no need to have it again in 19.
It's not initialized to anything, so it has an unspecified value.
It's true though that these variables (besides term) should have been declared later (when they are needed).
Just wait until problem 15! It's a hard one. I thought I had a clever recursive solution but it doesn't scale well enough, either. I'm pretty sure I know an algorithm that will work but I haven't had time to go back to it. I've been working on a Vim plugin for the past few days.