Monday 17 July 2017

Java Code to find the smallest integer that has n or more divisors

Problem:

Design and implement an algorithm that finds the smallest positive integer that has n or more divisors.

Solution:

package com.myprograms;

import java.util.Scanner;

public class SmallestPosInteger {

int input;
int result;

public static void main(String[] args) {
SmallestPosInteger smallestPosInteger = new SmallestPosInteger();
smallestPosInteger.getTheNumber();
smallestPosInteger.findTheSmallestInteger();
smallestPosInteger.printTheResult();
}

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

public void printTheResult(){
System.out.println("the smallest positive integer n with atleast num divisors. "+ result);
}

public void findTheSmallestInteger(){
int i = 1;
while(input > divisors(i))
{
i++;
}
result = i;
}

private int divisors(int num)
{
if(num < 1)
return 0;
int n=1, count = 0, trunc = (int) Math.sqrt(num);
while(n <= trunc)
{
if(num%n == 0)
{
if(num/n == n)
{
count += 1;
}
else
{
count += 2;
}
}
n += 1;
}
return count;
}


}


Output:

enter the number
4
the smallest positive integer n with atleast num divisors. 6

enter the number
6
the smallest positive integer n with atleast num divisors. 12

enter the number
24
the smallest positive integer n with atleast num divisors. 360


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...