Showing posts with label math. Show all posts
Showing posts with label math. Show all posts

Computing the polynomial mathematical function in java

Problem:

A polynomial function is a very famous mathematical function.
The greatest exponent, n, is called the degree of the polynomial. For example, p(x) = 7x4 2 is a
polynomial of degree 4. The simplest polynomials are constant polynomials such as p(x) = 6
(degree 0) and linear polynomials such as p(x) = 9x + 6 (degree 1). The unique zero polynomial
p(x) = 0 is defined to have degree 1. In this section we present a Polynomial class whose
instances represent mathematical polynomials and which supports the usual algebraic operations
on polynomials.
A polynomial can be regarded as a sum of distinct terms. A term is a mathematical function of
the form t (x) = cxe, where c is any real number and e is any nonnegative integer. The number c is
called the coefficient, and the number e is called the exponent.
To define a class whose objects represent polynomials, we use a linked list of Term objects.
For example, the polynomial p(x) = 3x2 2x + 5 could be represented as a list of three elements,
where the first element represents the term 3x2, the second element represents the term 2x, and
the third element represents the (constant) term 5.

Write a java program that computes the polynomial function.

Output:

Not applicable

Solution:

public class Polynomial {
private List<Term> list = new LinkedList<Term>();
public static final Polynomial ZERO = new Polynomial();
private Polynomial() { // default constructor
}
public Polynomial(double coef, int exp) {
if (coef != 0.0) {
list.add(new Term(coef, exp));
}
}
public Polynomial(Polynomial p) { // copy constructor
for (Term term : p.list) {
this.list.add(new Term(term));
}
}
public Polynomial(double... a) {
for (int i=0; i<a.length; i++) {
if (a[i] != 0.0) {
list.add(new Term(a[i], i));
}
}
}
public int degree() {
if (list.isEmpty()) {
return -1;
} else {
return list.get(list.size()-1).exp;
}
public boolean isZero() {
return list.isEmpty();
}
public Polynomial plus(Polynomial p) {
if (this.isZero()) {
return new Polynomial(p);
}
if (p.isZero()) {
return new Polynomial(this);
}
Polynomial q = new Polynomial();
ListIterator<Term> it = list.listIterator();
ListIterator<Term> itp = p.list.listIterator();
while (it.hasNext() && itp.hasNext()) {
Term term = it.next();
Term pTerm = itp.next();
if (term.exp < pTerm.exp) {
q.list.add(new Term(term));
itp.previous();
} else if (term.exp == pTerm.exp) {
q.list.add(new Term(term.coef + pTerm.coef, term.exp));
} else { // (term.exp > pTerm.exp)
q.list.add(new Term(pTerm));
it.previous();
}
}
while (it.hasNext()) {
q.list.add(new Term(it.next()));
}
while (itp.hasNext()) {
q.list.add(new Term(itp.next()));
}
return q;
}
public String toString() {
if (this.isZero()) {
return "0";
}
Iterator<Term> it = list.iterator();
StringBuilder buf = new StringBuilder();
boolean isFirstTerm = true;
while (it.hasNext()) {
Term term = it.next();
double c = term.coef;
int e = term.exp;
if (isFirstTerm) {
buf.append(String.format("%.2f", c));
isFirstTerm = false;
} else {
if (term.coef < 0) {
buf.append(String.format(" - %.2f", -c));
} else {
buf.append(String.format(" + %.2f", c));
}
}
if (e == 1) {
buf.append("x");
} else if (e > 1) {
buf.append("x^" + e);
}
}
return buf.toString();
}
private static class Term {
private double coef;
private int exp;
public Term(double coef, int exp) {
if (coef == 0.0 || exp < 0) {
throw new IllegalArgumentException();
}
this.coef = coef;
this.exp = exp;
}
public Term(Term that) { // copy constructor
this(that.coef, that.exp);
}
}
}
Read More

Compute GCD using three different methods in Java

Problem:

Compute GCD using three different methods in Java.

Output:

Not applicable.

Solution:

/**--------------------Method 1 ---------------*/
public class gcd_recursion_azzam
{
   public static int gcd(int m, int n, int i ) {
     
       if (m%i ==0 && n %i ==0)
         return i;
       else
         return gcd(m,n,--i);
  }
   
   public static void main(String[] args)
   {
     System.out.println(gcd(10,4,4));
   }
}
/**--------------------Method 2 ---------------*/
public class gcd_recursion_book
{
   public static int gcd(int m, int n) {
     
       if (m % n == 0) 
         return n;
       else if (m < n)
         return gcd(m,n);
       else
         return gcd(n, m%n);
     } 
   
   public static void main(String[] args)
   {
     System.out.println(gcd(10,4));
   }
}
/**--------------------Method 3 ---------------*/
public class gdc_recursion_online
{
   public static int gcd(int a, int b) {
     
       if (b==0) 
         return a;
       else
         return gcd(b, a % b);
     } 
   
   public static void main(String[] args)
   {
     System.out.println(gcd(10,4));
   }
}
Read More

Recursive Power Method in Java

Problem:

Write a recursive power method in Java.

Output:

Not applicable.

Solution:

public class x_y_power
{
  public static int power(int x, int y)
  {
    if (y == 0)
      return 1;
    
    else 
      return x*power(x , y - 1);
  }
Read More

Creating a Multiplication Table in Java

Problem:

Write an application called MultiplicationTable that asks the user to input a number N then creates a 2 dimensional array of size N X N and stores inside it the table of multiplication up to N.

Output:

Enter N: 4
Outputs:
1 2 3 4
2 4 12 8
3 6 9 12
4 8 12 16

Solution:

import java.util.Scanner;
public class Problem1 {
 public static void main(String[] args)
 {
  Scanner scan = new Scanner(System.in);
  int num = scan.nextInt();
  
  int[][] table = new int[num][num];
  
  for(int i=0; i<num; i++)
  {
   for(int j=0; j<num; j++)
   {
    table[i][j] = (i+1)*(j+1);
   }
  }
  
  for(int i=0; i<num; i++)
  {
   for(int j=0; j<num; j++)
   {
    System.out.print(table[i][j] + "\t");
   }
   System.out.println();
  }
  
 }
}
Read More

Creating a rectangle class in Java

Problem:

a. Create a class Rectangle. The class has attributes length and width, each of which defaults to 1. It has methods that calculate the perimeter and the area of the rectangle. It has set and get methods for both length and width. The set methods should verify that length and width are each floating-point numbers larger than 0.0 and less than 20.0.
b. Create a more sophisticated Rectangle class than the one you created in (a). This class stores only the Cartesian coordinates of the four corners of the rectangle. The constructor calls a set method that accepts four sets of coordinates and verifies that each of these is in the first quadrant with no single x- or y-coordinate larger than 20.0. The set method also verifies that the supplied coordinates do, in fact, specify a rectangle. Provide methods to calculate the length,width, perimeter and area. The length is the larger of the two dimensions. Include a predicate method isSquare which determines if the rectangle is a square.

Output:

Not needed.

Solution:

public class Rectangle
{
 private
  int width = 0, length = 0;
 
 public
  Rectangle(int width, int length)
  {
   setWidth(width);
   setLength(length);
  }
 
  void setWidth(int width)
  {
   this.width = width;
  }
  
  void setLength(int length)
  {
   this.length = length;
  }
  
  int getWidth()
  {
   return this.width;
  }
  
  int getLength()
  {
   return this.length;
  }
  
  int getPerimeter()
  {
   return 2*getWidth() + 2*getLength();
  }
  
  int getArea()
  {
   return getWidth()*getLength();
  }
  
  boolean isSquare()
  {
   return (getWidth() == getLength());
  }

 public static void main(String[] args)
 {
  Scanner scan = new Scanner(System.in);
  
  System.out.print("Enter width:");
  System.out.print("Enter length:");
  int width=scan.nextInt();
  int length=scan.nextInt();
  Rectangle rect = new Rectangle(width, length);
  System.out.println("Area: " + rect.getArea());
  System.out.println("Perimeter: " + rect.getPerimeter());
  
  if(rect.isSquare())
  {
   System.out.println("This is a square.");
  }
  else
  {
   System.out.println("This is not a square.");
  }
 }
}
Read More

Calculating the GCD of two numbers in Java

Problem:

The greatest common divisor (GCD) of two integers is the largest integer that evenly divides each of the two numbers. Write an application that reads two integers from the user and then prints their greatest common divisor. Implement this exercise using Functions.

Output:

Not needed.

Solution:

import java.util.Scanner;
public class problem4 
{
 public static void main(String[] args)
 {
  Scanner scan=new Scanner(System.in);
  int GCD=0,smallest;
  System.out.println("Enter the two numbers:");
  int num1=scan.nextInt();
  int num2=scan.nextInt();
  if(num1<num2)
   smallest=num1;
   
  else
   smallest=num2;
  
  for(int n=smallest;n>=1;n--)
  {
   if((num1%n==0) && (num2%n==0))
   {
    GCD=n;
    n=0;//to exit loop
   }
  }

  System.out.println("The GCD is: "+ GCD);
 }
}
Read More

Java > Logic-1 > teenSum (CodingBat Solution)

Problem:

Given 2 ints, a and b, return their sum. However, "teen" values in the range 13..19 inclusive, are extra lucky. So if either value is a teen, just return 19.

teenSum(3, 4) → 7
teenSum(10, 13) → 19
teenSum(13, 2) → 19


Solution:

public int teenSum(int a, int b) {
  int sum = a+b;
  if ((a >= 13 && a <= 19) || (b >= 13 && b <= 19))
    return 19;
  else
    return sum;
}
Read More

Java > Logic-1 > nearTen (CodingBat Solution)

Problem:

Given a non-negative number "num", return true if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2. See also: Introduction to Mod

nearTen(12) → true
nearTen(17) → false
nearTen(19) → true


Solution:

public boolean nearTen(int num) {
  if (num % 10 < 3 || num % 10 >=8)
    return true;
  else return false;
}
Read More

Java > AP-1 > hasOne (CodingBat Solution)

Problem:

Given a positive int n, return true if it contains a 1 digit. Note: use % to get the rightmost digit, and / to discard the rightmost digit.

hasOne(10) → true
hasOne(22) → false
hasOne(220) → false


Solution:

public boolean hasOne(int n) 
{
  while(n%10!=0||n==10)
  {
    if(n%10 == 1)
      return true;
    else
      n/=10;  
  }  
  
  return false;  
}
Read More

Java > Logic-2 > roundSum (CodingBat Solution)

Problem:

For this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a separate helper "public int round10(int num) {" and call it 3 times. Write the helper entirely below and at the same indent level as roundSum().

roundSum(16, 17, 18) → 60
roundSum(12, 13, 14) → 30
roundSum(6, 4, 4) → 10


Solution:

public int roundSum(int a, int b, int c) {
  return round10(a) + round10(b) + round10(c);
}

public int round10(int n) {
  if (n % 10 < 5)
    return n - (n%10);
  else
    return n + (10 - (n%10));
}
Read More

Java > Warmup-2 > has271 (CodingBat Solution)

Problem:

Given an array of ints, return true if it contains a 2, 7, 1 pattern -- a value, followed by the value plus 5, followed by the value minus 1. Additionally the 271 counts even if the "1" differs by 2 or less from the correct value.

has271({1, 2, 7, 1}) → true
has271({1, 2, 8, 1}) → false
has271({2, 7, 1}) → true


Solution:

public boolean has271(int[] nums) {
  int len = nums.length;

  for (int i = 0; i < nums.length - 1; i++) {   
    if (i+2 <= nums.length - 1){
      int j = Math.abs(nums[i] - 1);  
      int k = Math.abs(j - nums[i+2]);         
      if(nums[i+1] == nums[i]+5 && k <= 2)
        return true;      
    }    
          
  } return false;
}
Read More

Java > Warmup-1 > close10 (CodingBat Solution)

Problem:

Given 2 int values, return whichever value is nearest to the value 10, or return 0 in the event of a tie. Note that Math.abs(n) returns the absolute value of a number.

close10(8, 13) → 8
close10(13, 8) → 8
close10(13, 7) → 0


Solution:

public int close10(int a, int b) {
  int temp1 = Math.abs(a - 10);
  int temp2 = Math.abs(b - 10);

  if (temp1 == temp2)
    return 0;
  else if (temp1 > temp2)
    return b;
  else 
    return a;
}
Read More

Java > Warmup-1 > intMax (CodingBat Solution)

Problem:

Given three int values, a b c, return the largest.

intMax(1, 2, 3) → 3
intMax(1, 3, 2) → 3
intMax(3, 2, 1) → 3


Solution:

public int intMax(int a, int b, int c) {
  int temp1 = Math.max(a,b);
  int temp2 = Math.max(temp1, c);
  return temp2;
}
Read More

Java > Warmup-1 > or35 (CodingBat Solution)

Problem:

Return true if the given non-negative number is a multiple of 3 or a multiple of 5. Use the % "mod" operator -- see Introduction to Mod

or35(3) → true
or35(10) → true
or35(8) → false


Solution:

public boolean or35(int n) {
  return (n % 3 == 0) || (n % 5 == 0);
}
Read More

Java > Warmup-1 > nearHundred (CodingBat Solution)

Problem:

Given an int n, return true if it is within 10 of 100 or 200. Note: Math.abs(num) computes the absolute value of a number.

nearHundred(93) → true
nearHundred(90) → true
nearHundred(89) → false


Solution:

public boolean nearHundred(int n) {
  int sum1 = Math.abs(n - 100);
  int sum2 = Math.abs(n - 200);
  
  if (sum1 <= 10 || sum2 <= 10)
    return true;
  else
    return false;
}
Read More

Project Euler > Problem 45 > Triangular, pentagonal, and hexagonal (Java Solution)

Problem:

Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:

Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal Pn=n(3n[−]1)/2 1, 5, 12, 22, 35, ...
Hexagonal Hn=n(2n[−]1) 1, 6, 15, 28, 45, ...

It can be verified that T285 = P165 = H143 = 40755.

Find the next triangle number that is also pentagonal and hexagonal.


Solution:

1533776805


Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
 * Solution to Project Euler problem 45
 * By Nayuki Minase
 * 
 * http://nayuki.eigenstate.org/page/project-euler-solutions
 * https://github.com/nayuki/Project-Euler-solutions
 */


public final class p045 implements EulerSolution {
 
 public static void main(String[] args) {
  System.out.println(new p045().run());
 }
 
 
 public String run() {
  int i = 286;
  int j = 166;
  int k = 144;
  while (true) {
   long triangle = (long)i * (i + 1) / 2;
   long pentagon = (long)j * (j * 3 - 1) / 2;
   long hexagon  = (long)k * (k * 2 - 1);
   long min = Math.min(Math.min(triangle, pentagon), hexagon);
   if (min == triangle && min == pentagon && min == hexagon)
    return Long.toString(min);
   if (min == triangle) i++;
   if (min == pentagon) j++;
   if (min == hexagon ) k++;
  }
 }
 
}
Read More

Project Euler > Problem 47 > Distinct primes factors (Java Solution)

Problem:

The first two consecutive numbers to have two distinct prime factors are:

14 = 2 [×] 7
15 = 3 [×] 5

The first three consecutive numbers to have three distinct prime factors are:

644 = 2² [×] 7 [×] 23
645 = 3 [×] 5 [×] 43
646 = 2 [×] 17 [×] 19.

Find the first four consecutive integers to have four distinct prime factors. What is the first of these numbers?


Solution:

134043


Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
 * Solution to Project Euler problem 47
 * By Nayuki Minase
 * 
 * http://nayuki.eigenstate.org/page/project-euler-solutions
 * https://github.com/nayuki/Project-Euler-solutions
 */


public final class p047 implements EulerSolution {
 
 public static void main(String[] args) {
  System.out.println(new p047().run());
 }
 
 
 public String run() {
  for (int i = 2; ; i++) {
   if (       has4PrimeFactors(i + 0)
           && has4PrimeFactors(i + 1)
           && has4PrimeFactors(i + 2)
           && has4PrimeFactors(i + 3))
    return Integer.toString(i);
  }
 }
 
 
 private static boolean has4PrimeFactors(int n) {
  return countDistinctPrimeFactors(n) == 4;
 }
 
 
 private static int countDistinctPrimeFactors(int n) {
  int count = 0;
  for (int i = 2, end = Library.sqrt(n); i <= end; i++) {
   if (n % i == 0) {
    do n /= i;
    while (n % i == 0);
    count++;
    end = Library.sqrt(n);
   }
  }
  if (n > 1)
   count++;
  return count;
 }
 
}
Read More

Finding Mersenne Prime Numbers in Java

Problem:

A prime number is called a Mersenne prime if it can be written in the form for some positive integer p. Write a program that finds Mersenne primes numbers as seen in the output.


Output:

p 2^p-1
2 3
3 7
5 31
7 127
13 8191
17 131071
19 524287
31 2147483647


Solution:

public class MersennePrime
{
  public static boolean isPrime(int N)
  {
    for (int i = 2;i<=Math.sqrt(N);i++)
    {
      if (N%i == 0)
        return false;
    }
    return true;
  }
  
  public static void main (String[] args)
  {
    System.out.println("p" +"\t"+ "2^p-1");    
    for (int i =2;i<=34;i++)
    {
      if (isPrime(i) && isPrime((int) (Math.pow(2, i)-1)))
      {
          System.out.println(i +"\t" + (int) (Math.pow(2, i)-1));
      }
    }
  }
}

Read More

Printing Emirp Numbers in Java

Problem:

An emirp (prime spelled backward) is a nonpalindromic prime number whose reversal is also a prime. For example, 17 is a prime and 71 is a prime. So, 17 and 71 are emirps. Write a program that displays the first 100 emirps. Display 10 numbers per line and align the numbers properly. as follows:


Output:



Solution:

 //Happy note: based on our input, it's okay if we duplicate
 //palindromes, i.e. we can have both 17 and 71 among the 100
 //that means we have to code less than we would've if it
 //only wanted sets of palindromes
 import java.util.Scanner;  
 public class Emirp
 {  
        
      //To make things easier, let's just make
      //a method to determine if a number is a
      //prime or not instead of copying the code
      //into our loops
      public static boolean isPrime(int N)  
      {  
           //Here's a trick about numbers and their divisors:
           //We all know that a number like a number n can have 
           //as finite divisors 1, itself, and any number between
           //1 and n that divides n withou a remainder.
           //To find out if a number n has a divisor greater than 1
           //and less than itself (i.e., not prime) we can go throu
           //every number between 1 and n and check if we find at least
           //one divisor. But a shortcut to that is to check every 
           //number between 1 and n squared. For some reason
           //this is a valid math theorem, so just work with it
           //cz it'll involve less looping :)
           for(int i =2;i<=Math.sqrt(N);i++)   
           {  
                if(N%i==0)   
                {  
                     //Of course if we found out that it does
                     //divide n, then it is not prime so we should
                     //stop this method automatically
                     return false;  
                }  
           }  
           //And if we found nothing between 1 and n squared
           //then n truly is a prime
           return true;  
      }  
        
      //Just like we did with primeness
      //let's make a method for palindromes 
      //to save us time
      //All we need to input is the number itself
       public static int reverse (int N)  
      {  
           String str = Integer.toString(N);  
           String targetS = "";  
           {  
                for(int i =str.length()-1;i>=0;i--)  
                {  
                     targetS+= str.charAt(i);  
                }  
           }  
           return Integer.parseInt(targetS);  
      }  
     
      //Note: we want to get a NON-palindrome prime,
      //the best way to do this is to first check if 
      //a number is a prime and then seeing if it IS 
      //a palindrome. It's easier to make a method that
      //shows that it's prime than the converse. 
      

      //There are two common ways of testing palindromes
      //One is comparing and looping between each side of a word
      //through variables left and right, and the other method
      //is to create a string that has the reverse of our word
      //and comparing it with the original to see if the original
      //string is the same as its reverse
      //We'll use the second technique here just for convenience
      //and first try to find the reversed form
      //Note: we could've integrated this with the next palindrome method
      //but it's just always more neater to work with sets of methods
      //instead of just one method
      public static int reverse (int N)  
      {  
           //However, to reverse the digits in a int
           //we have to convert it into a String 
           //so that we can treat it like a set of characters
           String str = Integer.toString(N);  
 
          //Note: we can't remove things from a string variable
          //but just add, so we have to make a new empty String and add
          //to it the characters of our original string but in reverse
           String targetS = "";  
           
           //Since we're to reverse the original String
           //then we have to start from the last index/character
           //and make ourselves go to the left, while adding everything
           for(int i =str.length()-1;i>=0;i--)  
           {  
               targetS+= str.charAt(i);  
           }  
           //Since we want to return an int (cz we are working with
           //numbers) then we have to convert our reversed String
           //into an int variable with the following method:
           return Integer.parseInt(targetS);  
      }  

      //The reverse and prime methods are useless if there's no method
      //that will use them to see if is prime AND a palindrome
      //or not, so it's time for: 
      public static boolean isPalindromicPrime(int N)  
      {  
           //As expected, we need to convert to string
           String S = Integer.toString(N);  
           if (isPrime(N))  
           {  
                //Note: to convert a int or anything into a String, we can 
                //either use a method (Integer.toString(N), etc) or just append
                //our int to ""; both techniques work
                if(N.equalsIgnorecase(""+reverse(N))
                    return true
           }  
           else
                return false;  
      }  

      //Time to see if our N is prime, not a palindrome,
      //but has a prime number as a reversal
      public static boolean isEmirp(int N)  
      {  
           String S = Integer.toString(N);
           //Hint: always separate conditions with () in case you have
           //a condition that uses operators just to be safe/clear  
           if (isPrime(N) && isPrime(reverse(N)) && (isPalindromicPrime(N) == false))  
                return true;  
           else  
                return false;  
      }  
        
      //God... that was a lot, but we need our 100  
      public static void main (String[] args)  
      {  
           //We want the first 100 emirps so lets make an array
           //to store them 
           int[] pprime = new int[100];  
           //We need something to count how many emirps we've found
           int count =0;  
           //And now it's time to loop over every number above 2 to
           //find our emirps and store them till we reach the 100 count
           for (int pal =2;count<100;pal++)  
           {  
                if (isEmirp(pal))  
                {  
                     pprime[count] = pal;  
                     count++;  
                }   
           }
           
           //...We still gotta print out our 100 emirps     
           for(int i =0;i<100;i++)  
           {  
                //Well, we need to make it look like a table and
                //a table needs to have an ending and we need to start
                //a new line after every 10th emirp
                if ((i+1) % 10 == 0) 
                     System.out.println(pprime[i]);  
                else 
                     System.out.print(pprime[i] + "\t");  
           }  
      }  
        
   
 }  
Read More

Finding Perfect Numbers in Java

Problem:

A positive integer is called a perfect number if it is equal to the sum of all of its positive divisors, excluding itself. For example, 6 is the first perfect number because 6 = 3 + 2 + 1. The next is 28 = 14 + 7 + 4 + 2 + 1. There are four perfect numbers less than 10000. Write a program to find all these four numbers.


Output:

6
28
496
8128


Solution:

public class PerfectNumbers
{
  public static int sumDivisors(int n )
  {
    int sum = 0;
    for (int i =n-1;i>=1;i--)
    {
      if(n%i == 0)
      {
        sum+=i;
      }
    }
    return sum;
  }
  public static void main(String[] args)
  {
    for (int i =1;i<10000;i++)
    {
      if(sumDivisors(i) == i)
        System.out.println(i);
    }
  }
}
Read More

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact