Thursday 22 June 2017

Java Code to find the largest factorial number present as a factor in n.

Problem:

Design an algorithm which, given some integer n, finds the largest factorial number present as a factor in n.

Solution:

package com.myprograms;

import java.util.Scanner;

public class FactorialComputation4 {

int n;

public static void main(String[] args) {

FactorialComputation4 factorialComputation3 = new FactorialComputation4();
factorialComputation3.getTheValues();
factorialComputation3.printTheResult();
}

private void getTheValues(){
Scanner s = new Scanner(System.in);
System.out.println("enter a  number");
n = s.nextInt();
s.close();
}

private int findFactorial(){
if(n <= 0)
return -1;
int i = 1;
int j = 2;
while(n%j == 0)
{
if(i*j <= n)
i = i*j;
j++;
}
return i;
}

private void printTheResult(){
System.out.println("The largest factorial number as a factor is: " + findFactorial());
}
}


Output:

enter a  number
12
The largest factorial number as a factor is: 6


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