patterncMinor
Find all multiples of a number in given range in reverse order
Viewed 0 times
numberorderreverseallrangemultiplesfindgiven
Problem
I have a problem set which requires me to print all the multiples of a number in given range in reverse order.
So far I have tried this but not sure it is optimized or not!
So far I have tried this but not sure it is optimized or not!
#import
#import
@implementation TestObj
int main()
{
int limit = 0;
int divisor = 5;
printf("enter a number : ");
scanf("%d",&limit);
printf("enter divisor : ");
scanf("%d",&divisor);
printf("Multiples of %d in reverse order till limit %d are : ",divisor, limit);
for(int i = limit/divisor; i > 0 ; i--){
printf("%d ",i*divisor);
}
return 0;
}
@endSolution
Multiplication is not a very cheap operation.
Subtraction is much cheaper.
It will be a better and cleaner algorithm to start from the highest multiple,
and then keep subtracting until reaching 0:
The improvements:
Subtraction is much cheaper.
It will be a better and cleaner algorithm to start from the highest multiple,
and then keep subtracting until reaching 0:
int truncatedCount = limit / divisor;
int highestMultiple = truncatedCount * divisor;
for (int multiple = highestMultiple; multiple > 0; multiple -= divisor) {
printf("%d ", multiple);
}The improvements:
- multiplication replaced by subtractions
- more meaningful variable names (instead of
i, for example)
- more conventional spacing (around operators and around
(...)and{ ... }
Code Snippets
int truncatedCount = limit / divisor;
int highestMultiple = truncatedCount * divisor;
for (int multiple = highestMultiple; multiple > 0; multiple -= divisor) {
printf("%d ", multiple);
}Context
StackExchange Code Review Q#97559, answer score: 4
Revisions (0)
No revisions yet.