Ad Home

Theme images by kelvinjay. Powered by Blogger.

Travel

Header Ads

Java

Selenium

UFT

Framework

General QA Concept

BDD

» » How to calculate an Abundant and Deficient Number in java




An Abundant number is defined as a number if sum of all its positive divisor except itself is more than the number itself.
An deficient number is defined as a number if sum of all its positive divisor except itself is less than the number itself. Example-12.
The factors of 12 are-1,2,3,4,6,12.
To be a abundant number we need to add the divisors except that number so the sum is-1+2+3+4+6=16 which is greater than 12.
So it is an abundant number.
Again take an example of 16
The factors are-1,2,4,8,16
To be a abundant number we need to add the divisors except that number so the sum is-1+2+4+8=15 which is less than 16.
So it is not an abundant number rather it is a deficient no .

Let us think  the logic-- 1. Get the range from user.
2. Get the number inside the range starting from start range(I will use 1)
3. Find out the positive divisors of the number
4. Add all the positive divisors except itself
5. Check if the sum of the divisors is greater than that number.
6. If the checking is passes to become an abundant number ...save it
7. Increment a number
8. If it is inside the range perform Step 9 or else perform Step-10
9. Follow Step 3.
10. Exit
So i can write a function for step no 3 to 10 because that is repetitive.

Let us code:

For logic 2--


//I am assuming the lower range as 1 or else please replace 1 with your lower range      
for (int i=1 ;i<=your_positive_range ;i++)
        {
        checkAbundant(i);
    }
Now how the checkAbundant code will look like-
// a is the number coming from your previous function for which we need to check if it is an abundant number or not.
public void checkAbundant(int a)
  {
         //pos is a temporary variable to store the sum of the divisors(positive)
         int pos=0;
        // Same logic by which we derived the factors of a given number
        //As per the rule we need to exclude the number itself so the loop goes to number-1 so i<a will take care of that 
         for (int i=1;i<a;i++) {
            if((a%i)==0) {
                   pos=pos+i;
             
            }
        }
            if(pos>a)
            {
                System.out.println("this is  a abundant no"+a);
            }

         else
            {
                System.out.println("this is  a deficient no"+a);
            }

    }
Code yourself and Check out how many abundant and deficient number you get below 1000.

«
Next
Newer Post
»
Previous
Older Post

No comments:

Leave a Reply