Given a positive number n, write a function isMultipleof5(int n) that returns true if n is multiple of 5, otherwise false. You are not allowed to use % and / operators.
Method 1 (Repeatedly subtract 5 from n)
Run a loop and subtract 5 from n in the loop while n is greater than 0. After the loop terminates, check whether n is 0. If n becomes 0 then n is multiple of 5, otherwise not.
#include/* assumes that n is a positive integer */bool isMultipleof5 (int n){ while ( n > 0 ) n = n - 5; if ( n == 0 ) return true; return false;}/* Driver program to test above function */int main(){ int n = 19; if ( isMultipleof5(n) == true ) printf("%d is multiple of 5\n", n); else printf("%d is not a multiple of 5\n", n); return 0;} |
Method 2 (Convert to string and check the last character)
Convert n to a string and check the last character of the string. If the last character is ’5′ or ’0′ then n is multiple of 5, otherwise not.
#include#include#include/* Assuming that integre takes 4 bytes, there can be maximum 10 digits in a integer */# define MAX 11bool isMultipleof5(int n){ char str[MAX]; itoa(n, str, MAX); int len = strlen(str); /* Check the last character of string */ if ( str[len-1] == '5' || str[len-1] == '0' ) return true; return false;}/* Driver program to test above function */int main(){ int n = 19; if ( isMultipleof5(n) == true ) printf("%d is multiple of 5\n", n); else printf("%d is not a multiple of 5\n", n); return 0;} |
Thanks to Baban_Rathore for suggesting this method.
Method 3 (Set last digit as 0 and use floating point trick)
A number n can be a mulpile of 5 in two cases. When last digit of n is 5 or 10. If last bit in binary equivalent of n is set (which can be the case when last digit is 5) then we multiply by 2 using n<<=1 to make sure that if the number is multpile of 5 then we have the last digit as 0. Once we do that, our work is to just check if the last digit is 0 or not, which we can do using float and integer comparison trick.
#includebool isMultipleof5(int n){ /* If n is a multiple of 5 then we make sure that last digit of n is 0 */ if ( (n&1) == 1 ) n <<= 1; float x = n; x = ( (int)(x*0.1) )*10; /* If last digit of n is 0 then n will be equal to (int)x */ if ( (int)x == n ) return true; return false;}/* Driver program to test above function */int main(){ int i = 19; if ( isMultipleof5(i) == true ) printf("%d is multiple of 5\n", i); else printf("%d is not a multiple of 5\n", i); getchar(); return 0;} |
No comments:
Post a Comment