Answer to Question #249890 in Java | JSP | JSF for I AM LEGEND

Question #249890
Write a class Factors to model the factors of an integer1: • have attribute storing the integer whose factors are to be calculated. • have boolean array attribute ( factors ) where each element record whether that index is a factor of the integer i.e factor[5] = true • have a constructor which will assign the stored integer attribute to a user specified value and create the factors array NB: what is the size of this factors array? • have a method that calculates the factors of the stored integer and stores this is the Boolean array mentioned above. This is done by dividing the integer by all the integers less than itself and checking if there is a remainder. • have a method that prints out the factors of the stored integer to the screen i.e. “Factors of 120 are: 2, 3, 5, “ • have a method that takes another Factor object and prints out the common factors between that object the current object. • have a method that determines whether the integer is a perfect number by looking at the factors array.
1
Expert's answer
2021-10-12T00:36:48-0400


package factors;


import java.util.Scanner;




public class Factors {


    private int data;
    private boolean [] factors;
    private int [] arr;
    private int x;
    Factors(int d){
        data = d;
        factors = new boolean[data];
        arr = new int[data];
        x=0;
    }
    
    void populate(){
       int n = 1;
       int f = 0;
       
       while(n<=data){
           if(data %n==0){
               arr[f] = n;
               factors[f]  = true;
               f++;
               
           }
           
           n++;
       } 
        
       
        
       
        
    }
    
    void display(){
        System.out.printf("Factors of %d are: ", data);
        for(int i=0; i<arr.length; i++){
            if(arr[i]==0){
                
            }
            else{
                System.out.printf("%d, ",arr[i]);
                x++;
            }
            
        }
    }
    void perfect_number(){
        int sum = 0;
        int n = x- 2;
        
        for(int i=0; i<=n;i++ ){
            sum += arr[i];
        }
        
        if(sum==data){
            System.out.printf("\n%d, is a perfect number\n", data);
        }
    }
    public static void main(String[] args) {
        
        System.out.println("Enter a number\n");
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
       Factors f = new Factors(n);
       f.populate();
       f.display();
       f.perfect_number();
    }
    
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS