Sunday 16 July 2017

Java Code to find the smallest divisor of an integer

Problem:

Given an integer n devise an algorithm that will find its smallest exact divisor other than one.


Solution:

package com.myprograms;

import java.util.Scanner;

public class SmallestDivisor {

int n;
int result;

public static void main(String[] args) {
SmallestDivisor smallestDivisor = new SmallestDivisor();
smallestDivisor.getTheNumber();
smallestDivisor.findTheSmallestDivisor();
smallestDivisor.printTheResult();
}

public void getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("enter the number");
n = s.nextInt();
s.close();
}

public void findTheSmallestDivisor(){
if((n % 2) != 0){
int r = (int) Math.sqrt(n);
int d = 3;
while((n % d) != 0 && d < r){
d = d + 2;
}
if(n%d == 0){
result = d;
}
else{
result = 1;
}
}
else{
result = 2;
}
}

public void printTheResult(){
System.out.println("the smallest divisor of " + n + " is: " + result);
}

}


Output:

enter the number
1024
the smallest divisor of 1024 is: 2

enter the number
63
the smallest divisor of 63 is: 3


enter the number
1013
the smallest divisor of 1013 is: 1


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...