Monday 31 July 2017

Java Code to find out the prime factors of an integer

Problem:

Design and implement an algorithm to find out the prime factors of an integer


Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FindThePrimeFactors {

int n;
List<Integer> primeNumbers = new ArrayList<Integer>();
List<Integer> primeFactors = new ArrayList<Integer>();

public static void main(String[] args) {
FindThePrimeFactors findThePrimeFactors = new FindThePrimeFactors();
findThePrimeFactors.getTheNumber();
findThePrimeFactors.findThePrimeFactors();
findThePrimeFactors.printPrimeFactors();
}

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

public void findThePrimeFactors(){
for (int i = 2; i <= n; i++) {
            while (n % i == 0) {
                primeFactors.add(i);
                n /= i;
            }
        }
}

public void printPrimeFactors(){
System.out.println("the prime factors are: " + primeFactors);
}
}


Output:

enter the number
12
the prime factors are: [2, 2, 3]


enter the number
147
the prime factors are: [3, 7, 7]

enter the number
17
the prime factors are: [17]


Saturday 29 July 2017

Java Code to generate the Mersenne primes in the first n integers


Problem:

The largest known prime numbers are called the Mersenne Primes. They are of the form 2 power p - 1 where p is prime.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class MersennePrime {

int n;
List<Integer> primeNumbers = new ArrayList<Integer>();
List<Integer> mersennePrimeNumbers = new ArrayList<Integer>();

public static void main(String[] args) {
MersennePrime mersennePrime = new MersennePrime();
mersennePrime.getTheNumber();
mersennePrime.findThePrimeNumbers();
mersennePrime.printThePrimeNumbers();
mersennePrime.findMersennePrime();
mersennePrime.printTheMersennePrimeNumbers();
}

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

public void findMersennePrime(){
for(Integer i : primeNumbers){
mersennePrimeNumbers.add(((int)Math.pow(2, i)) - 1);
}
}

public void findThePrimeNumbers(){
for (int i = 2; i < n; i++) {
if(isPrime(i)){
primeNumbers.add(i);
}
}
}

public boolean isPrime(int number){
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(number); i++) {
if(number%i == 0){
isPrime = false;
}
}
return isPrime;
}

public void printThePrimeNumbers(){
System.out.println("The prime numbers are " + primeNumbers);
}

public void printTheMersennePrimeNumbers(){
System.out.println("The mersenne prime numbers are " + mersennePrimeNumbers);
}

}


Output:

enter the number
20
The prime numbers are [2, 3, 5, 7, 11, 13, 17, 19]
The mersenne prime numbers are [3, 7, 31, 127, 2047, 8191, 131071, 524287]


Thursday 27 July 2017

Java Code to find the lucky numbers for the given n value

Problem:

Another interesting sequence of numbers is produced by starting out with the list of all integers
1,2,3, ......n. From this list every second number is removed to produce a new list. From the new list every third number is removed to give yet another list. Every fourth number is removed from this list and so the process continues. The numbers that remain after this process are called the lucky numbers. Design and implement an algorithm to list the lucky numbers in the first n integers.

Solution:

package com.myprograms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class LuckyNumbers {

public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter the Number of Elements : ");
        int n=Integer.parseInt(br.readLine());
        int a[]=new int[n];
        int c=n;
        for(int i=0;i<n;i++)
        {
            a[i]=i+1;
        }
        int del=1;
        System.out.println("\nLucky Number Operation :\n");
        while(del<n)
        {
            for(int i=del; i<n; i+=del)
            {
                for(int j=i; j<n-1; j++)
                {
                    a[j]=a[j+1];
                }
                n--;
            }
            del++;
            for(int i=0; i<n; i++)
            {
                System.out.print(a[i]+"   ");
            }
            System.out.println();
        } //end of while
        System.out.print("\nHence, the Lucky Numbers Less than "+c+" are : ");
        for(int i=0; i<n; i++)
        {
            System.out.print(a[i]+"   ");
        }
    }

}


Output:

Enter the Number of Elements : 20

Lucky Number Operation :

1   3   5   7   9   11   13   15   17   19  
1   3   7   9   13   15   19  
1   3   7   13   15   19  
1   3   7   13   19  

Hence, the Lucky Numbers Less than 20 are : 1   3   7   13   19  

Monday 24 July 2017

Java Code to find the prime numbers using sieving algorithm

Problem:

It is possible to implement a sieving algorithm which crosses out each composite (non-prime) number exactly once rather than a number of times. The algorithm is based on the idea that any non-prime x can be written as x=p power k * q where k>= 1 and q is a prime >= p. Try to implement this algorithm.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FindThePrimeNumber3 {
List<Boolean> input = new ArrayList<Boolean>();
List<Integer> resultList = new ArrayList<Integer>();
int n;

public static void main(String[] args) {
FindThePrimeNumber3 findThePrimeNumber2 = new FindThePrimeNumber3();
findThePrimeNumber2.getTheNumber();
findThePrimeNumber2.findPrimeNumbers();
findThePrimeNumber2.printTheResult();


}

public void getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("Enter number : ");
n = s.nextInt();
input.add(Boolean.FALSE);
input.add(Boolean.FALSE);
for(int i = 2; i<= n; i++){
input.add(Boolean.TRUE);
}
s.close();
}

public void findPrimeNumbers(){
for (int i = 2; i*i <= n; i++) {
if(input.get(i)){
for(int j = i*2; j<= n; j = j+i){
input.set(j, Boolean.FALSE);
}
}
}
}

public void printTheResult(){
for(int i = 2; i < input.size(); i++){
if(input.get(i)){
resultList.add(i);
}
}
System.out.println("the prime numbers upto given number are " + resultList);
}

}


Output:

Enter number :
20
the prime numbers upto given number are [2, 3, 5, 7, 11, 13, 17, 19]


Java Code to establish all the primes in the first n positive integers

Problem:

Design and implement an algorithm to establish all the primes in the first n positive integers.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FindThePrimeNumber2 {
List<Integer> resultList = new ArrayList<Integer>();
int n;

public static void main(String[] args) {
FindThePrimeNumber2 findThePrimeNumber2 = new FindThePrimeNumber2();
findThePrimeNumber2.getTheNumber();
findThePrimeNumber2.findPrimeNumbers();
findThePrimeNumber2.printTheResult();


}

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

public void findPrimeNumbers(){
for (int i = 2; i < n; i++) {
if(isPrime(i)){
resultList.add(i);
}
}
}

public boolean isPrime(int i){
for(int j = 2; j<= Math.sqrt(i); j++){
if(i%j == 0){
return false;
}
}
return true;
}

public void printTheResult(){
System.out.println("the prime numbers upto given number are " + resultList);
}

}


Output:

Enter number :
20
the prime numbers upto given number are [2, 3, 5, 7, 11, 13, 17, 19]

Enter number : 
10
the prime numbers upto given number are [2, 3, 5, 7]


Sunday 23 July 2017

Java Code to compute the two fractions sum in terms of the smallest common denominator.

Problem:

Given the two fractions a/b and c/d, design and implement an algorithm that computes their sum in terms of the smallest common denominator.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class LeastCommonDenominator {

int firstFractionNumerator;
int secondFractionNumerator;
int firstFractionDenominator;
int secondFractionDenominator;
String firstFractionNumber;
String secondFractionNumber;

List<Integer> firstNumberMultiples = new ArrayList<Integer>();
List<Integer> secondNumberMultiples = new ArrayList<Integer>();
int leastCommonDenominator;
int positionOfLCMInFirstNumberMultiples;
int positionOfLCMInSecondNumberMultiples;
String sumOfGivenFractions;

public static void main(String[] args) {
LeastCommonDenominator leastCommonDenominator = new LeastCommonDenominator();
leastCommonDenominator.getTheNumbers();
leastCommonDenominator.findFisrFractionDenominatorMultiples();
leastCommonDenominator.findSecondFractionDenominatorMultiples();
leastCommonDenominator.findLeastCommonMultiple();
leastCommonDenominator.findFractionsSum();
leastCommonDenominator.printTheResult();
}

public void getTheNumbers(){
Scanner scanner = new Scanner(System.in);

System.out.println("enter the first fraction");
firstFractionNumber = scanner.nextLine();
String[] firstFractionStrings = firstFractionNumber.split("/");
firstFractionNumerator = Integer.parseInt(firstFractionStrings[0]);
firstFractionDenominator = Integer.parseInt(firstFractionStrings[1]);

System.out.println("enter the scond fraction");
secondFractionNumber = scanner.nextLine();
String[] secondFractionStrings = secondFractionNumber.split("/");
secondFractionNumerator = Integer.parseInt(secondFractionStrings[0]);
secondFractionDenominator = Integer.parseInt(secondFractionStrings[1]);

scanner.close();
}

public void findFisrFractionDenominatorMultiples(){
for(int i = 1; i <= 20; i++){
firstNumberMultiples.add(firstFractionDenominator * i);
}
}

public void findSecondFractionDenominatorMultiples(){
for(int i = 1; i<= 20; i++){
secondNumberMultiples.add(secondFractionDenominator * i);
}
}

public void findLeastCommonMultiple(){
for(Integer i: firstNumberMultiples){
for(Integer j: secondNumberMultiples){
if(i == j){
positionOfLCMInFirstNumberMultiples = firstNumberMultiples.indexOf(i) + 1;
positionOfLCMInSecondNumberMultiples = secondNumberMultiples.indexOf(j) + 1;
leastCommonDenominator = i;
break;
}
}
if(leastCommonDenominator != 0){
break;
}
}
}

public void findFractionsSum(){
sumOfGivenFractions = (firstFractionNumerator * positionOfLCMInFirstNumberMultiples) + (secondFractionNumerator * positionOfLCMInSecondNumberMultiples) + "/" + leastCommonDenominator;
}

public void printTheResult(){
System.out.println(firstFractionDenominator + " multiples are " + firstNumberMultiples);
System.out.println(secondFractionDenominator + " multiples are " + secondNumberMultiples);
System.out.println("the Least common multiple of " + firstFractionDenominator + " and " + secondFractionDenominator + " is " + leastCommonDenominator);
System.out.println("the sum of given fractions is " + sumOfGivenFractions);
}

}


Output:

enter the first fraction
2/21
enter the scond fraction
1/6
21 multiples are [21, 42, 63, 84, 105, 126, 147, 168, 189, 210, 231, 252, 273, 294, 315, 336, 357, 378, 399, 420]
6 multiples are [6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96, 102, 108, 114, 120]
the Least common multiple of 21 and 6 is 42
the sum of given fractions is 11/42


Java Code to compute the smallest common multiple of two integers

Problem:

Design an algorithm to compute the smallest common multiple of two integers n and p. The SCM is defined as the smallest integer m such that n and p divide exactly into m.

Solution:

package com.myprograms;

import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class LeastCommonMultiple {

int firstNumber;
int secondNumber;
Set<Integer> firstNumberMultiples = new TreeSet<Integer>();
Set<Integer> secondNumberMultiples = new TreeSet<Integer>();
int result;

public static void main(String[] args) {
LeastCommonMultiple leastCommonMultiple = new LeastCommonMultiple();
leastCommonMultiple.getTheNumbers();
leastCommonMultiple.findFisrNumberMultiples();
leastCommonMultiple.findSecondNumberMultiples();
leastCommonMultiple.findLeastCommonMultiple();
leastCommonMultiple.printTheResult();
}

public void getTheNumbers(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the first number");
firstNumber = scanner.nextInt();
System.out.println("enter the scond number");
secondNumber = scanner.nextInt();
scanner.close();
}

public void findFisrNumberMultiples(){
for(int i = 1; i <= 50; i++){
firstNumberMultiples.add(firstNumber * i);
}
}

public void findSecondNumberMultiples(){
for(int i = 1; i<= 50; i++){
secondNumberMultiples.add(secondNumber * i);
}
}

public void findLeastCommonMultiple(){
for(Integer i: firstNumberMultiples){
for(Integer j: secondNumberMultiples){
if(i == j){
result = i;
break;
}
}
if(result != 0){
break;
}
}
}

public void printTheResult(){
System.out.println(firstNumber + " multiples are " + firstNumberMultiples);
System.out.println(secondNumber + " multiples are " + secondNumberMultiples);
System.out.println("the Least common multiple of " + firstNumber + " and " + secondNumber + " is " + result);
}

}


Output:

enter the first number
5
enter the scond number
8
5 multiples are [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
8 multiples are [8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 128, 136, 144, 152, 160]
the Least common multiple of 5 and 8 is 40


enter the first number
4
enter the scond number
6
4 multiples are [4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80]
6 multiples are [6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96, 102, 108, 114, 120]
the Least common multiple of 4 and 6 is 12



Java Code to Prove that consecutive Fibonacci numbers are relatively prime.

Problem:

It is well known that adjacent Fibonacci numbers do not share a common divisor greater than 1 (they are relatively prime). Design an algorithm and implement that tests this observation for the first n integers.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class GCDOfFibonaciNumbers {

int n;
List<Integer> fibonacciList = new ArrayList<Integer>();

public static void main(String[] args) {
GCDOfFibonaciNumbers gcdOfFibonaciNumbers = new GCDOfFibonaciNumbers();
gcdOfFibonaciNumbers.getTheNumbers();
gcdOfFibonaciNumbers.fibonacciNumbers();
gcdOfFibonaciNumbers.findDivisors();
}

public void getTheNumbers(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the n value");
n = scanner.nextInt();
scanner.close();
}

public void fibonacciNumbers(){
fibonacciList.add(0);
fibonacciList.add(1);
for(int i = 2; i<n;i++){
fibonacciList.add(fibonacciList.get(i-1) + fibonacciList.get(i-2));
}
System.out.println("the fibonacci numbers are " + fibonacciList);
}

public void findGCD(int largerNumber, int smallNumber){
System.out.print("the GCD of " + largerNumber +" and " + smallNumber + " is: ");
int reminder = largerNumber % smallNumber;
while(reminder != 0){
largerNumber = smallNumber;
smallNumber = reminder;
reminder = largerNumber % smallNumber;
}
System.out.println(smallNumber);
}

public void findDivisors(){
for(int i = 0; i<fibonacciList.size() - 1; i++){
findGCD(fibonacciList.get(i), fibonacciList.get(i+1));
}
}
}


Output:

enter the n value
15
the fibonacci numbers are [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
the GCD of 0 and 1 is: 1
the GCD of 1 and 1 is: 1
the GCD of 1 and 2 is: 1
the GCD of 2 and 3 is: 1
the GCD of 3 and 5 is: 1
the GCD of 5 and 8 is: 1
the GCD of 8 and 13 is: 1
the GCD of 13 and 21 is: 1
the GCD of 21 and 34 is: 1
the GCD of 34 and 55 is: 1
the GCD of 55 and 89 is: 1
the GCD of 89 and 144 is: 1
the GCD of 144 and 233 is: 1
the GCD of 233 and 377 is: 1

Friday 21 July 2017

Java Code to find the Greatest Common Divisor of n positive non-zero integers

Problem:

Design an algorithm and implement that will find the Greatest Common Divisor of n positive non-zero integers

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class GCDOfNNumbers {

int n;
List<Integer> list = new ArrayList<Integer>();

int smallNumber;
int largerNumber;
int result;
int input1;
int input2;

public static void main(String[] args) {
GCDOfNNumbers gcdOfTwoNumbers = new GCDOfNNumbers();
gcdOfTwoNumbers.getTheNumbers();
gcdOfTwoNumbers.findGCD();
gcdOfTwoNumbers.printTheResult();

}

public void getTheNumbers(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the n value");
n = scanner.nextInt();
for(int i = 0;i<n;i++){
System.out.println("enter number");
list.add(scanner.nextInt());
}
Collections.sort(list);
scanner.close();
}

public void findGCD(){
int reminder = 0;
int res = 0;
for(int i = 0; i< n - 1; i++){
reminder = list.get(i + 1) % list.get(i);
while(reminder != 0){
list.set(i+1, list.get(i));
list.set(i, reminder);
reminder = list.get(i + 1) % list.get(i);
res = list.get(i);
}
}
result = res;
}

public void printTheResult(){
System.out.println("the Greatest Common Divisor of given numbers is: " + result);
}

}


Output:

enter the n value
4
enter number
2
enter number
4
enter number
6
enter number
8
the Greatest Common Divisor of given numbers is: 2



enter the n value
4
enter number
35
enter number
95
enter number
215
enter number
65
the Greatest Common Divisor of given numbers is: 5


enter the n value
5
enter number
221
enter number
39
enter number
4199
enter number
247
enter number
91
the Greatest Common Divisor of given numbers is: 13

Thursday 20 July 2017

Java Code to find the Greatest Common Divisor without using Modulo function

Problem:

Design and implement a gcd algorithm that does not use either division or modulo functions.

Solution:

package com.myprograms;

import java.util.Scanner;

public class GCDOfTwoNumbersWithoutDivision {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter first number");
int n1 = scanner.nextInt();
System.out.println("enter second number");
int n2 = scanner.nextInt();
while(n1 != n2)
        {
            if(n1 > n2)
                n1 = n1-n2;
            else
                n2 = n2-n1;
        }
        System.out.print("the Greatest Common Divisor of given number is " + n1);
scanner.close();

}
}


Output:

enter first number
30
enter second number
18
the Greatest Common Divisor of given number is 6

Tuesday 18 July 2017

Java Code to find the Greatest Common Divisor of Two Integers

Problem:

Given two positive non-zero integers n and m design an algorithm and implement their greatest common divisor.

Solution:

package com.myprograms;

import java.util.Scanner;

public class GCDOfTwoNumbers {

int smallNumber;
int largerNumber;
int result;
int input1;
int input2;

public static void main(String[] args) {
GCDOfTwoNumbers gcdOfTwoNumbers = new GCDOfTwoNumbers();
gcdOfTwoNumbers.getTheNumbers();
gcdOfTwoNumbers.findGCD();
gcdOfTwoNumbers.printTheResult();

}

public void getTheNumbers(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter first number");
input1 = scanner.nextInt();
System.out.println("enter second number");
input2 = scanner.nextInt();
if(input1>input2){
largerNumber = input1;
smallNumber = input2;
}
else {
largerNumber = input2;
smallNumber = input1;
}
scanner.close();
}

public void findGCD(){
int reminder = largerNumber % smallNumber;
while(reminder != 0){
largerNumber = smallNumber;
smallNumber = reminder;
reminder = largerNumber % smallNumber;
}
result = smallNumber;
}

public void printTheResult(){
System.out.println("the Greatest Common Divisor of " + input1 + " and " + input2 + " is: " + result);
}

}


Output:

enter first number
18
enter second number
24
the Greatest Common Divisor of 18 and24 is: 6


enter first number
18
enter second number
30
the Greatest Common Divisor of 18 and 30 is: 6


enter first number
54
enter second number
24
the Greatest Common Divisor of 54 and 24 is: 6

Java Code to implement Fermat's algorithm

Problem:

An algorithm due to Fermat can be used to find the largest factor f (less than or equal to squareroot(n)) of an odd integer.

Solution:

package com.myprograms;

import java.util.Scanner;

public class FermatAlgorithm {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
        System.out.println("Enter odd number");
        long N = scan.nextLong();
        FermatAlgorithm fermatAlgorithm = new FermatAlgorithm();
        fermatAlgorithm.findFermatFactor(N);
        scan.close();

}

public boolean isSquare(long N)
    {
        long sqr = (long) Math.sqrt(N);
        if (sqr * sqr == N || (sqr + 1) * (sqr + 1) == N)
            return true;
        return false;
    }

public void display(long r1, long r2)
    {
        System.out.println("\nRoots = "+ r1 +" , "+ r2);  
    }

public void findFermatFactor(long N)
   {
       long a = (long) Math.ceil(Math.sqrt(N));
       long b2 = a * a - N;
       while (!isSquare(b2))
       {
           a++;
           b2 = a * a - N;
       }
       long r1 = a - (long)Math.sqrt(b2);
       long r2 = N / r1;
       display(r1, r2);
   }

}



Output:

Enter odd number
5959

Roots = 59 , 101


Monday 17 July 2017

Java Code to find the maximum divisors in the given range

Problem:

For the integers in the given range find the number that has the most divisors.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class MaximumDivisors {

int lowerLimit;
int upperLimit;
List<Integer> divisors = new ArrayList<Integer>();
List<Integer> resultList = new ArrayList<Integer>();
int result;

public static void main(String[] args) {
MaximumDivisors maximumDivisors = new MaximumDivisors();
maximumDivisors.getTheLimits();
maximumDivisors.findTheMaximumDivisors();
maximumDivisors.printTheResult();
}

public void getTheLimits(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter lower limit value");
lowerLimit = scanner.nextInt();
System.out.println("enter upper limit value");
upperLimit = scanner.nextInt();
scanner.close();
}

public void findTheMaximumDivisors(){
for(int i = lowerLimit; i<= upperLimit; i++){
resultList.add(findExactDivisors(i));
}
Collections.sort(resultList);
result = resultList.get(resultList.size() - 1);
}

public int findExactDivisors(int n){
divisors = new ArrayList<Integer>();
for(int i = 1; i<=n; i++ ){
if(n%i == 0){
divisors.add(i);
}
}
return divisors.size();
}

public void printTheResult(){
System.out.println("the maximum number of divisors in the set " + lowerLimit + " " + upperLimit +" is: " + result);
}


}


Output:

enter lower limit value
1
enter upper limit value
10
the maximum number of divisors in the set 1 10 is: 4

enter lower limit value
1
enter upper limit value
100
the maximum number of divisors in the set 1 100 is: 12

enter lower limit value
10
enter upper limit value
48
the maximum number of divisors in the set 10 48 is: 10


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


Sunday 16 July 2017

Java Code to produce a list of all exact divisors of a given positive integer n.

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]


enter the number
1024
the list of exact divisors of 1024 is[2, 4, 8, 16, 32, 64, 128, 256, 512]


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


Java Code to finds the integer whose square is closest to but greater than the number input as data

Problem:

Design an algorithm that finds the integer whose square is closest to but greater than the number input as data.

Solution:

package com.myprograms;

import java.util.Scanner;

public class FindNearestSquaretNumber {

int n;
int result;

public static void main(String[] args) {
FindNearestSquaretNumber findNearestSquaretNumber = new FindNearestSquaretNumber();
findNearestSquaretNumber.getTheNumber();
findNearestSquaretNumber.isGreaterThanInput();
findNearestSquaretNumber.printTheResult();
}

public void printTheResult(){

if(result != 0){
System.out.println("Nearest square root of n and gretaer than n value is:  " + result);;
}
else {
System.out.println("could not found the greater than n value ");;
}
}

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

public int findNearestSquare(int num){

//find the square root
int num1 = (int) Math.sqrt(num);
// if square root square’s is num… given number is a Perfect Square return the same //number
if(num1 * num1 == num)
return num;
else{
//else calculate floor_square and ceil_square get absolute difference between num
// which is minimum that is the nearest square num
int floorSquare = num1 * num1;
int ceilingSquare = (num1 + 1) * (num1 + 1);
if(Math.abs(floorSquare-num) < Math.abs(ceilingSquare -num) )
return floorSquare;
else
return ceilingSquare;
}

}

public void isGreaterThanInput(){
result = findNearestSquare(n);
if(result < n){
result = 0;
}
}
}


Output:

enter the number
3
Nearest square root of n and gretaer than n value is:  4

enter the number
23
Nearest square root of n and gretaer than n value is:  25





Saturday 15 July 2017

Java Code to find the reciprocal of a number

Problem:

Design and implement an algorithm to compute the reciprocal of a number.

Solution:
package com.myprograms;

import java.util.Scanner;

public class Reciprocal {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter the number: ");
String n = s.nextLine();
System.out.println("the reciprocal of " + n + " is " + findTheReciprocal(n));
s.close();
}

public static String findTheReciprocal(String n){
String result = "";
if(n.contains("/")){
String[] strings = n.split("/");
result = strings[1] + "/" + strings[0];
}
else{
result = "1" + "/" + n;
}
return result;
}
}


Output:

enter the number:
3/4
the reciprocal of 3/4 is 4/3


enter the number: 
8
the reciprocal of 8 is 1/8


Java Code to find out the Geometric Mean

Problem:

The geometric mean is used to measure central tendency. It is defined as

G.M = nth root of (x1 * x2 * x3 ......* xn)

Develop an algorithm to input n numbers and compute their geometric mean.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class GeometricMean {

int n;
List<Double> numbers = new ArrayList<Double>();

public static void main(String[] args) {
GeometricMean geometricMean = new GeometricMean();
geometricMean.getTheNumbers();
System.out.println("the GM: " + geometricMean.findGM());
}

public void getTheNumbers(){
Scanner s = new Scanner(System.in);
System.out.println("how many numbers: ");
n = s.nextInt();
for(int i = 0; i<n; i++){
System.out.println("enter the numbers: ");
numbers.add(s.nextDouble());
}
s.close();
}

public double findGM(){
return Math.pow(findTheProductOfnumbers(), 1.0/n);
}

public double findTheProductOfnumbers(){
double product = 1.0;
for(Double n: numbers){
product = product * n;
}
return product;
}

}


Output:


how many numbers:
2
enter the numbers:
2
enter the numbers:
18
the GM: 6.0


how many numbers: 
3
enter the numbers: 
10
enter the numbers: 
51.2
enter the numbers: 
8
the GM: 15.999999999999998


how many numbers: 
5
enter the numbers: 
1
enter the numbers: 
3
enter the numbers: 
9
enter the numbers: 
27
enter the numbers: 
81
the GM: 9.000000000000002


Java Code to find out the square root of a number

Problem:

Given a number m devise an algorithm to compute its square root.

Solution:

package com.myprograms;

import java.util.Scanner;

public class SquareRootOfNumber {

int n;
public static void main(String[] args) {
SquareRootOfNumber squareRootOfNumber = new SquareRootOfNumber();
squareRootOfNumber.getTheNumber();
squareRootOfNumber.findSquareRoot();

}

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

public void findSquareRoot(){
double g1 = 0;
double g2 = n/2;
while(g1-g2 != 0){
g1 = g2;
g2 = (g1+n/g1)/2;
}
System.out.println("the result is: " + g2);
}

}


Output:

enter the number which need to find the square root
225
the result is: 15.0


enter the number which need to find the square root
36
the result is: 6.0


enter the number which need to find the square root
10
the result is: 3.162277660168379


Friday 14 July 2017

Java Code that reads a given set of data and decides whether or not it may contain decimal data.

Problem:

Design an algorithm that reads a given set of data and decides whether or not it may contain decimal data.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class DetermineCharacterSet {

String string;
List<Integer> digits = new ArrayList<Integer>();

public static void main(String[] args) {
DetermineCharacterSet characterToIntegerConversion = new DetermineCharacterSet();
characterToIntegerConversion.getTheNUmberAsString();
characterToIntegerConversion.convertToDecimal();
characterToIntegerConversion.printTheResult();

}

public void getTheNUmberAsString(){
Scanner s = new Scanner(System.in);
System.out.println("enter the characters" );
string = s.nextLine();
s.close();
}

public void convertToDecimal(){
for(Character c: string.toCharArray()){
digits.add((int)c);
}
}

public void printTheResult(){
boolean flag = false;
for(Integer n : digits){
if(n >= 48 && n<=57){
flag = true;
}
}
System.out.println("The ascii values are: " + digits);
System.out.println("is given set contains decimals ?? : " + flag);
}
}


Output:

enter the characters
hello
The ascii values are: [104, 101, 108, 108, 111]
is given set contains decimals ?? : false


enter the characters
hell99
The ascii values are: [104, 101, 108, 108, 57, 57]
is given set contains decimals ?? : true


Java Code to convert a decimal representation for a number to the corresponding character string representation.

Problem:

Design an algorithm to convert a decimal representation for a number to the corresponding character string representation.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class DecimalToCharatcerConversion {

Integer number;
List<Integer> digits = new ArrayList<Integer>();
List<Character> result = new ArrayList<Character>();

public static void main(String[] args) {
DecimalToCharatcerConversion characterToIntegerConversion = new DecimalToCharatcerConversion();
characterToIntegerConversion.getTheNUmberAsString();
characterToIntegerConversion.convertToCharacter();
characterToIntegerConversion.printTheResult();

}

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

public void convertToCharacter(){
for(Character c: number.toString().toCharArray()){
digits.add((int)c);
}
}

public void printTheResult(){
for(int n : digits){
result.add((char)(n));
}
System.out.println("The ascii values are: " + digits);
System.out.println("the character values are: "  + result);
}
}


Output:

enter the number
198765
The ascii values are: [49, 57, 56, 55, 54, 53]
the character values are: [1, 9, 8, 7, 6, 5]


Java Code to convert to decimal where the input character string contains a decimal point.

Problem:

Design an algorithm that will handle conversions to decimal where the input character string may contains a decimal point.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class DecimalCharacterToIntegerConversion {

static String numberAsString;
List<Integer> integralPart = new ArrayList<Integer>();
List<Integer> fractionalPart = new ArrayList<Integer>();

public static void main(String[] args) {
DecimalCharacterToIntegerConversion characterToIntegerConversion = new DecimalCharacterToIntegerConversion();
characterToIntegerConversion.getTheNUmberAsString();
String[] number = numberAsString.split("\\.");
characterToIntegerConversion.convertIntegralPartToDecimal(number[0]);
characterToIntegerConversion.convertFractionalPartToDecimal(number[1]);
characterToIntegerConversion.printTheResult();

}

public void getTheNUmberAsString(){
Scanner s = new Scanner(System.in);
System.out.println("enter the characters which contain decimal point" );
numberAsString = s.nextLine();
s.close();
}

public void convertIntegralPartToDecimal(String s){
for(Character c: s.toCharArray()){
integralPart.add((int)c);
}
}

public void convertFractionalPartToDecimal(String s){
for(Character c: s.toCharArray()){
fractionalPart.add((int)c);
}
}

public void printTheResult(){
int integralNumber = 0;
int fractionallNumber = 0;
for(Integer n : integralPart){
integralNumber = integralNumber * 10 + n;
}
for(Integer n : fractionalPart){
fractionallNumber = fractionallNumber * 10 + n;
}
System.out.println("The ascii values for integralPart: " + integralPart);
System.out.println("The ascii values for fractionalPart: " + fractionalPart);
System.out.println("the decimal number is: "  + integralNumber + "." + fractionallNumber);
}
}


Output:

enter the characters which contain decimal point
1984.84
The ascii values for integralPart: [49, 57, 56, 52]
The ascii values for fractionalPart: [56, 52]
the decimal number is: 55312.612


Thursday 13 July 2017

Java Code to Convert the character to number.

Problem:

Given the character representation of an integer convert it to its conventional decimal format.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CharacterToIntegerConversion {

String string;
List<Integer> digits = new ArrayList<Integer>();

public static void main(String[] args) {
CharacterToIntegerConversion characterToIntegerConversion = new CharacterToIntegerConversion();
characterToIntegerConversion.getTheNUmberAsString();
characterToIntegerConversion.convertToDecimal();
characterToIntegerConversion.printTheResult();

}

public void getTheNUmberAsString(){
Scanner s = new Scanner(System.in);
System.out.println("enter the characters" );
string = s.nextLine();
s.close();
}

public void convertToDecimal(){
for(Character c: string.toCharArray()){
digits.add((int)c);
}
}

public void printTheResult(){
int number = 0;
for(Integer n : digits){
number = number * 10 + n;
}
System.out.println("The ascii values are: " + digits);
System.out.println("the decimal number is: "  + number);
}
}


Output:

enter the characters
1987
The ascii values are: [49, 57, 56, 55]
the decimal number is: 55315

enter the characters
hello
The ascii values are: [104, 101, 108, 108, 111]
the decimal number is: 1152991


Wednesday 12 July 2017

Java Code to converts the decimal fraction to binary fraction

Problem:

Design an algorithm that accepts as input a decimal fraction and converts it to the corresponding binary fraction of a fixed accuracy.

Solution:

package com.myprograms;

import java.io.ObjectInputStream.GetField;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class DecimalFractionToBinaryFraction {

static double number;
List<Integer> integralPart = new ArrayList<Integer>();
List<Integer> fractionalPart = new ArrayList<Integer>();
int precesionLimit;
public static void main(String[] args) {
DecimalFractionToBinaryFraction decimalFractionToBinaryFraction = new DecimalFractionToBinaryFraction();
decimalFractionToBinaryFraction.getTheNumber();
decimalFractionToBinaryFraction.convertToBinaryFraction();
String result = decimalFractionToBinaryFraction.getTheIntegralPartResult() + "." + decimalFractionToBinaryFraction.getTheFractionalPartResult();
System.out.println("the converted number is: " + result);
}

public void getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("enter the decimal fraction: ");
number = s.nextDouble();
System.out.println("enter the precesion limit value: ");
precesionLimit = s.nextInt();
s.close();
}

public void convertToBinaryFraction(){
String[] numbers = new Double(number).toString().split("\\.");
int q = Integer.parseInt(numbers[0]);
for(int i = 0; q!= 0; i++){
integralPart.add(q%2);
q=q/2;
}

int fractionalNumber = Integer.parseInt(numbers[1]);
double fractionalNumber2 = Double.parseDouble("0." + fractionalNumber);
String[] fractionalNumbers;
for(int k = 1; k <= precesionLimit; k++){
fractionalNumber2 = fractionalNumber2* 2;
fractionalNumbers = new Double(fractionalNumber2).toString().split("\\.");
fractionalPart.add(Integer.parseInt(fractionalNumbers[0]));
fractionalNumber2 = Double.parseDouble("0." + fractionalNumbers[1]);
}
}

public int getTheIntegralPartResult(){
int number = 0;
for(int i = integralPart.size() - 1; i >= 0; i--){
number = number * 10 + (integralPart.get(i));
}
return number;
}

public int getTheFractionalPartResult(){
int number = 0;
for(int i = 0; i <fractionalPart.size(); i++){
number = number * 10 + (fractionalPart.get(i));
}
return number;
}
}


Output:

enter the decimal fraction:
6.986
enter the precesion limit value:
8
the converted number is: 110.11111100

Tuesday 11 July 2017

Java Code to convert decimal number to BCD representation.

Problem:

Design an algorithm that accepts as input a decimal number and converts it to the binary-coded decimal (bcd) representation. In the bcd scheme each digit is represented by a 4-digit binary code.

Solution:

package com.myprograms;

import java.util.Scanner;

public class BCD {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter decimal value");
int n = s.nextInt();
String bcd = "";
while(n != 0){
int r = n%10;
String temp = Integer.toBinaryString(r);
while(temp.length() < 4){
temp = "0" + temp;
}
bcd = temp + bcd;
n = n/10;
}
System.out.println("the bcd number is :" + bcd);
}
}


Output:

enter decimal value
67
the bcd number is :01100111


enter decimal value
194
the bcd number is :000110010100


Monday 10 July 2017

Java Code for base conversion.

Problem:

Design an algorithm to convert a number to be in any base up to 36.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class BaseConversion {

static String n;
static int outputBase;
static int inputBase;
List<Character> digits = new ArrayList<Character>();
static char[] result;
public static void main(String[] args) {
BaseConversion baseConversion = new BaseConversion();
baseConversion.getTheNumber();
result = baseConversion.baseConversion(n.toCharArray(), inputBase, outputBase);
baseConversion.printTheResult("the converted number is: ");

}

public void getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("what is your input base??");
inputBase = s.nextInt();
System.out.println("what is your expected output base??");
outputBase = s.nextInt();
System.out.println("enter the number");
n = s.next();
s.close();
}

public void printTheResult(String message){
System.out.print(message + " ");
for(Character c: result){
System.out.print(c);
}
}

private char intToChar(int i)
{
if(i >= 0 && i <= 9)
return (char)(i + 48);
else if(i >= 10 && i <= 35)
return (char)(i + 55);
else
return (char)(i);

}

private int charToInt(char c)
{
if(c >= '0' && c <= '9')
return (int)(c - 48);
else if(c >= 'A' && c <= 'Z')
return (int)(c - 55);
else if(c >= 'a' && c <= 'z')
return (int)(c - 87);
else
return 0;
}

char[] baseConversion(char num[], int ibase, int fbase)
{
int n=toDecimal(num, ibase);
char[] arr;
arr = decimalToBase(n, fbase);
return arr;
}

char[] decimalToBase(int num, int base)
{
if(base>36 || base<2)
return new char['0'];
int rem, i=0;
char[] arr = new char[100];
char[] arr2 = new char[100];
while(num != 0)
{
rem = num%base;
arr[i]=intToChar(rem);
num = num/base;
i++;
}
int j;
for(j=0; j<i; j++)//Reverse the arr[]
arr2[j] = arr[i-j-1];
return arr2;
}

int toDecimal(char num[], int base)
{
if(base > 36 || base < 2)
return -1;
int sum = 0;
for(int k = 0; k<num.length; k++){
sum = sum*base + charToInt(num[k]);
}
return sum;
}
}


Output:

what is your input base??
10
what is your expected output base??
8
enter the number
93
the converted number is:  135


what is your input base??
10
what is your expected output base??
2
enter the number
93
the converted number is:  1011101

what is your input base??
10
what is your expected output base??
16
enter the number
93
the converted number is:  5D


what is your input base??
2
what is your expected output base??
10
enter the number
1011101
the converted number is:  93


what is your input base??
2
what is your expected output base??
8
enter the number
1011101
the converted number is:  135

what is your input base??
2
what is your expected output base??
16
enter the number
1011101
the converted number is:  5D




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