Program - projecteuler.net
Write a program in matlab on the following question
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: 1
3: 1,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?
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,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?
Solution
In this program we will directly use the functions which we have defined earlier. For this program we will have to generate triangle numbers, and number of divisors of a given number to accomplish the task.
But I have written functions for number of divisors in three different methods. Here I will use the second method because the result took only few milliseconds and the other two took some time to do so.
The post you have to take a look at to understand this program are as follows:
Program
number = 0; i = 1; while numberofdivisors2(number) < 500 number = number+i i = i+1; end fprintf('The triangle number which has factors greater than 500 is %d\n',number);
To download this program for your use click here: factortrianglenumbers.m
Explanation
This program is very simple if you have understood about the above stated functions.So lets directly jump into the while loop iterations
First Iteration
During the first iteration the condition is satisfied and the computer digs deep into the program. It will increase the value of number from number = number+i and the value of i to i = i+1The same iterations will continue until the number of divisors of the given numbers will be less than 500.
If you have any more doubt please do contact me so that it will be useful for all others also. You can contact me here: contact me
The above code was highlighted using hilite.me
This problem has been taken from projecteuler.net and can be found here: problem 12
If you want to download this post and read it offline then you can do it from here: problem12_projecteuler_matlab.pdf
Run the program and comment below the output you are getting for a given input.
Keywords: problem12, projecteuler.net, matlab, highly divisible triangle numbers