Saturday, March 7, 2015

Calculating the HCF and LCM of two numbers

Here is the program to calculate the Highest Common Factor (HCF -- also known as Greatest Common Divisor) and Lowest Common Multiple (LCM) of two numbers. The code is extremely simple.

Code

#include <stdio.h>

int main()
{
    unsigned int a, b, i, hcf;
   
    printf("Enter two positive integers > 0: ");
    scanf("%d%d", &a, &b);
   
    for(i=1; i<=(a<b? a: b); i++)
    {
        if(!(a%i) && !(b%i))
        {
            hcf = i;
        }
    }
   
    printf("\nThe HCF of %d and %d is %d\n", a, b, hcf);
    printf("The LCM of %d and %d is %d\n", a, b, ((a*b)/hcf));
   
    return 0;
}



Explanation

HCF is obtained by dividing both numbers with all natural numbers less than the smallest one and choosing the last common factor (which will be the highest) encountered in the for loop. [The expression (a<b? a: b) chooses the smallest of a and b. The special operator ?: is technically known as conditional operator.]
LCM is calculated using the formula LCM = (a*b)/HCF.

Output

Enter two positive integers > 0: 4 6

The HCF of 4 and 6 is 2
The LCM of 4 and 6 is 12

Friday, March 6, 2015

Number/Currency to Words Conversion

This program helps us to convert a number (<1000) into words. That is, you give 912 and it says 'nine hundred and twelve!'

Code

/* 25 February, 2015 */
/* Updated on 21 October, 2015 */

#include <stdio.h>

int main()
{
char ones[][10] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
char tenAbove[][10] = {"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
char tens[][10] = {"ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};

int amt;

printf("Enter the amount (<10,000): ");
scanf("%d", &amt);

if(!amt)
{
printf("zero\n");
return 0;
}

if(amt/1000)
{
printf("%s thousand", ones[(amt/1000)-1]);
amt %= 1000;

if(amt) { printf(" "); }
}

if(amt/100)
{
printf("%s hundred", ones[(amt/100)-1]);
amt-=((amt/100)*100);

if(amt) { printf(" and "); }
}

if(amt/10)
{
if(((amt/10)==1) && (amt%10)) /* eleven to nineteen */
{
printf("%s\n", tenAbove[amt-11]);
return 0;
}

printf("%s", tens[(amt/10)-1]);
amt-=((amt/10)*10);

if(amt)
{
printf(" ");
}
}

if(amt)
{
printf("%s", ones[amt-1]);
}

printf("\n");

return 0;
}

Output

Enter the amount (<10,000): 1914
one thousand nine hundred and fourteen