C008 An interactive C program to check whether given two numbers are amicable numbers or not

By | August 12, 2013

Amicable numbers are two numbers so related that the sum of the proper divisors of the one is equal to the other, unity being considered as a proper divisor but not the number itself.

Let’s identify variables needed for this program.
First two variables will be the one which will save the values entered by the user and it will be NUM1, NUM2. Other two variables will be i,j which will be for FOR Loops. Last variable will be holding sum of  all the divisors of two numbers and it will be SUM1 and SUM2  so in all SIX variables.
The identified variables are NUM1,NUM2, i,j,SUM1,SUM2.

Now, Selection of data type is int data type due to the values expected are decimals and they will be holding smaller values so int data type is sufficient.

In this program there is a requirement of generating the divisors. Here we have to Check the values from 1 to the given number. It indicates LOOP is to be taken. Best Loop for such kind of condition is FOR Loop.
Loop selected is FOR Loop.

Now give the user a message to enter a value and scan the input from the user and save it in NUM1 and NUM2 variables.
for(i=0;i<NUM;i++) this FOR loop will give you DIVIDE ERROR. So be careful while initializing i=1 instead of i=0.
For Loop will start with 1 to NUM-1.To identify whether the number is divisor or not. We have to divide that number by given number(NUM1 and NUM2). If the remainder is zero than number entered is an divisor and if the remainder is not zero than number is not a divisor. This can be achieved by % (modulus) operator which is giving us the remainder.

The condition will be NUM1%i and NUM2%j in FOR Loops. If the remainder will be zero, INSTEAD of printing the number divisible as output values in this program, we will sum the divisors generated and save it in SUM1 and SUM2 by equation SUM1=SUM1+i and SUM2=SUM2+j.

If the total sum of divisor of a given number is equal to the given number itself than check this condition by NUM1==SUM2 && NUM2==SUM1 and if its equal than print the message TWO NUMBERS ARE AMICABLE NUMBERS else print message  TWO NUMBERS ARE NOT AMICABLE NUMBERS.

  1. #include<stdio.h>
  2. void main()
  3. {
  4. int NUM1,NUM2,i,j,SUM1=0,SUM2=0;
  6. scanf("%d",&NUM1);
  7. scanf("%d",&NUM2);
  8. for(i=1;i<NUM1;i++)
  9. {
  10. if(NUM1%i==0)
  11. {
  12. SUM1=SUM1+i;
  13. }
  14. }
  15. for(j=1;j<NUM2;j++)
  16. {
  17. if(NUM2%j==0)
  18. {
  19. SUM2=SUM2+j;
  20. }
  21. }
  22. if(NUM1==SUM2 && NUM2==SUM1)
  23. {
  24. printf("\n%d AND %d ARE AMICABLE NUMBERS",NUM1,NUM2);
  25. }
  26. else
  27. {
  28. printf("\n%d AND %d ARE NOT AMICABLE NUMBERS",NUM1,NUM2);
  29. }
  30. getch();
  31. }





Note:- To understand program for sequence in detail Please SEARCH numerically example: C001, C002, etc.

Leave a Reply