I need to write a code to find numbers divisible by 7 and multiples of 5 from 1500:2700. How do I preallocate line 4 for speed and is my code the most efficient way to solve
4 Commenti
Hi @Cade ,
You asked, “I need to write a code to find numbers divisible by 7 and multiples of 5 from 1500:2700. How do I preallocate line 4 for speed and is my code the most efficient way to solve”
Please see my response to your comments below.
After analyzing your code below,
result = []; for num = 1500:2700 if mod(num, 7) == 0 && mod(num, 5) == 0 result = [result, num]; end end disp('Numbers between 1500 and 2700 that are divisible by 7 and multiples of 5:'); disp(result);
Your code is initializing an empty array result and appending qualifying numbers to it. However, dynamically resizing arrays in MATLAB can be inefficient due to memory reallocation during each append operation and I do concur with @dpb comments.
Here is my recommendations for improvement mentioned below.
Preallocation: Preallocate the array to avoid repeated resizing. Since you know the range (1500 to 2700), you can estimate the maximum number of elements that will be added. The total count of integers in this range is 201, but not all will meet your criteria.
Efficient Filtering: Instead of checking each number individually, you can create a vector of numbers that are multiples of both 7 and 5 directly.
Algorithm Optimization: To find numbers divisible by both 7 and 5, you can calculate their least common multiple (LCM), which is 35. This allows you to iterate only through multiples of 35.
Here’s a refined version of your code with preallocation:
% Preallocate result array assuming a rough upper limit max_size = floor((2700 - 1500) / 35) + 1; % Estimate upper limit based on LCM result = zeros(1, max_size); % Preallocate with zeros
index = 1; % Index for result array for num = 1500:2700 if mod(num, 35) == 0 % Check divisibility by LCM of 7 and 5 result(index) = num; % Store number in preallocated array index = index + 1; % Increment index for next entry end end
% Trim result array to actual size result = result(1:index-1);
disp('Numbers between 1500 and 2700 that are divisible by 7 and multiples of 5:'); disp(result);
Please see attached.
So, in the refined code above, the result array is now preallocated with an estimated size based on the number of expected valid entries. It checks for mod(num, 35) == 0, reducing the number of checks needed. An index variable keeps track of where to insert new numbers into the preallocated array, making sure no empty slots remain at the end.
Please let me know if you have any further questions.
Risposte (2)
0 Commenti
0 Commenti
Vedere anche
Categorie
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!