Problem:
Design an algorithm and implement to produce a list of all exact divisors of a given positive integer n.
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ListOfExactDivisors {
int input;
List<Integer> divisors = new ArrayList<Integer>();
public static void main(String[] args) {
ListOfExactDivisors listOfExactDivisors = new ListOfExactDivisors();
listOfExactDivisors.getTheNumber();
listOfExactDivisors.findExactDivisors();
listOfExactDivisors.printTheResult();
}
public void getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("enter the number");
input = s.nextInt();
s.close();
}
public void findExactDivisors(){
for(int i = 2; i<input; i++ ){
if(input%i == 0){
divisors.add(i);
}
}
}
public void printTheResult(){
System.out.println("the list of exact divisors of " + input + " is" + divisors);
}
}
Output:
enter the number
36
the list of exact divisors of 36 is[2, 3, 4, 6, 9, 12, 18]
Design an algorithm and implement to produce a list of all exact divisors of a given positive integer n.
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ListOfExactDivisors {
int input;
List<Integer> divisors = new ArrayList<Integer>();
public static void main(String[] args) {
ListOfExactDivisors listOfExactDivisors = new ListOfExactDivisors();
listOfExactDivisors.getTheNumber();
listOfExactDivisors.findExactDivisors();
listOfExactDivisors.printTheResult();
}
public void getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("enter the number");
input = s.nextInt();
s.close();
}
public void findExactDivisors(){
for(int i = 2; i<input; i++ ){
if(input%i == 0){
divisors.add(i);
}
}
}
public void printTheResult(){
System.out.println("the list of exact divisors of " + input + " is" + divisors);
}
}
Output:
enter the number
36
the list of exact divisors of 36 is[2, 3, 4, 6, 9, 12, 18]
enter the number
1024
the list of exact divisors of 1024 is[2, 4, 8, 16, 32, 64, 128, 256, 512]
No comments:
Post a Comment