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

JAVA PRACTICE EXAM

JAVA PRACTICE  EXAM
Know that how good you are in programming

Problem A [Two’s Power]
Write a program that reads an integer n and checks whether n is a power of 2 (powers of 2 are 1,2,4,8,16,32, …). The output of your program is either “yes” or “no”.

public class LAU1
{
  public static void main (String[] args)
  {
    java.util.Scanner scan = new java.util.Scanner(System.in);
    int n = scan.nextInt();
    while (n >= 2)
    {
      if(n%!= 0)
        break;
      if (n%== 0)
        n/=2;
    }
    
    if (n == 1System.out.println("yes");
    else
      System.out.println("no");
  }
Problem B [No Duplicates]
Write a program that read a string str and prints a string obtained from str by removing/ignoring duplicates. For example, if str is abbacdcae, then your program prints abcde. In other words, only the first occurrence of a character is printed.
 


import java.util.Scanner;

public class LAU2
{
  public static void main (String[] args)
  {
    String target = "";
    Scanner scan = new Scanner (System.in);
    String S = scan.nextLine();
    for (int i =0;i<S.length();i++)
    {
      boolean so = true;
      for (int j = ; j<i;j++)
      {
        if (S.charAt(i== S.charAt(j))
          so = false;
      }
      if (sotarget += S.charAt(i);

    }
    
    System.out.print(target);
  }
}



Problem C [Integer Mirror]
Write a program that reads an integer N followed by N positive integers. For each entered integer, your program prints (on a new line) its digits in reverse. For example:
Input                          
3                                 
35423                         
7                                 
98710789
Output
32453
7
98701789


  import java.util.Scanner;
public class LAU3
{
  public static void main (String[] args)
  {
    Scanner scan = new Scanner (System.in);
    int N  = scan.nextInt();
    String[] nums = new String[N];
    for (int i =0;i<N;i++)
    {
      nums[i= scan.next();
    }
    
    for (int i = 0;i<N;i++)
    {
      for (int j =nums[i].length()-1;j>=0;j--)
      {
        System.out.print(nums[i].charAt(j));
      }
      System.out.println();
    }
  }
}



Problem D [Prime Frequency]
Write a program that reads positive integers from the keyboard until the user enters 0. Then the program prints the number of prime numbers entered. Here is a sample:
Input                           Output


2 3 5 0                         3



public class LAU4
{
  public static boolean isPrime(int n)
  {
    if(n ==|| n == )
      return false;
    for (int i =2;i<n;i++)
    {
      if (n%i == 0)
        return false;
    }
    return true;
  }
  public static void main (String[] args)
  {
    java.util.Scanner scan = new java.util.Scanner(System.in);
    int i = -1;
    int count = 0;
    while i != 0)
    {
      i = scan.nextInt();
      if (isPrime(i)) count++;
    }
    System.out.println(count);
  }
  
}


Problem E [Palindromes]

Write a program that reads an integer N followed by N strings. For each string, your program prints yes or no according whether the string is a palindrome or not. Here is a sample:

3
kayak                           yes
palindrome                    no
wow                             yes
Input                           Output


public class LAU5
{
  public static boolean isPalindrome(String str)
  {
    for (int i = 0;i<str.length()-1;i++)
    {
      if (str.charAt(i== str.charAt(str.length()-1-i))
        return true;
    }
    return false;
  }
  public static void main (String[] args)
  {
    java.util.Scanner scan = new java.util.Scanner(System.in);
    int N = scan.nextInt();
    
    for (int i =0;i<N;i++)
    {
      String temp = scan.next();
      if (isPalindrome(temp)) System.out.println("yes");
      else
        System.out.println("no");
        
    }
  }
}



Problem F [Flipped Star Triangles]
Complete the following program by writing the method starTriangle that takes an integer i and draws a flipped triangle (as shown below) of height i that is filled with stars. The main method (below) calls starTriangle N times, each time with one of the numbers between 1 and N. For example, if N is 3, the program calls starTriangle 3 times and prints:
                  
*****
 ***
   *

public static void main(String[] args) {
      Scanner input = new Scanner(system.in);
int N = input.nextInt();
for(int i = 1; i <= N; i++){
            starTriangle(i);
            System.out.println();
      }
}


Problem G [Fibonacci Number]
Complete and submit the following program by writing the boolean method isFib, which takes a positive integer n and checks whether n is one of the Fibonacci numbers (1,1,2,3,5,8,13,…).


public class FibNum

Input                           Output
3
2                                  yes
10                                No
13                                Yes

 
{
public static boolean isFib(int n)
{
}

public static void main(String[] args)
{
                                Scanner input = new Scanner(System.in);
int n, testnums = input.nextInt();
                                for(int j = 1; j <= testnums; j++)
{
n = input.nextInt();
if(isFib(n))
System.out.println(“Yes”);
else         System.out.println(“No”);
       
}
}
}


import java.util.Scanner;

public class LAU7
{
public static boolean isFib(int n)

  int a = 1
  int b =1;
  int c = 0;
  for (int i = 0;c<=n;i++)
  {
    c = a+b;
    a = b;
    b = c;
  if (c==n)
    return true;
  }
  return false;
}

public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);
int n, testnums = input.nextInt();
    for(int j = 1; j <= testnums; j++)
{
n = input.nextInt();
if(isFib(n))
System.out.println("Yes");
else   System.out.println("No");
        
}
}
}


Problem H [Longest Natural Successors]
Two consecutive integers are natural successors if the second is the successor of the first in the sequence of natural numbers (1 and 2 are natural successors). Write a program that reads a number N followed by N integers, and then prints the length of the longest sequence of consecutive natural successors. Example:
Input                                     Output
7 2 3 5 6 7 9 10                       3

import java.util.Scanner;

public class LAU8
{
  public static void main (String[] args)
  {
    Scanner scan = new Scanner (System.in);
    int N = scan.nextInt();
    int[] nums = new int[N];
    for (int i =0;i<N;i++)
    {
      nums[i= scan.nextInt();
    }
    int MAX = 0;
    int count = 0;
    for (int i =0;i<N-1;i++)
    {
      if (nums[i== nums[i+1])
      {
        count+=1;
        if (count > MAX)
          MAX = count;
      }
      
      if (nums[i1  != nums[i+1])
      {
        count = 0;
      }
      
    }
    if (MAX == 0MAX = -1;
    System.out.println(MAX+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

Simple Clock Countdown Simulation in Java

Problem:

Write a program that prompts the user to enter the number of seconds, displays a message at every second, and terminates when the time expires.


Output:

Enter the number of seconds: 10
10 seconds remaining
9 seconds remaining
8 seconds remaining
7 seconds remaining
6 seconds remaining
5 seconds remaining
4 seconds remaining
3 seconds remaining
2 seconds remaining
1 second remaining


Solution:

public class CountdownClock
{
  public static void main(String[] args)
  {
    java.util.Scanner scan = new java.util.Scanner(System.in);
    System.out.print("Enter the number of seconds: ");
    int seconds = scan.nextInt();
    for (int i =seconds;i>0;i--)
    {
      if (i != 1)
        System.out.println(i + " seconds remaining");
      else
        System.out.println(i + " second remaining");

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

Computing the Exponential "e" in Java

Problem:

You can computer e using the following Taylor series. Write a program that displays the  e value for  i 10000, 20000, and ... , 100000. Initialize e and item to be 1 and keep adding a new item to e.


Solution:

public class {

  public static double calFactorial(int n)
  {
    double out=1;
    for (int i =n;i>=1;i--)
    {
      out*=i;
    }
    return out;
  }
 public static void main (String[] args)
  {
    double e =1;
    for (int i =10000;i<=100000;i+=10000)
    {
      for (int j =1;j<=i;j++)
      {
        e+= 1.0/calFactorial(j);
      }
      System.out.println("For i = " + i + ", " +
          "e has a value of " + e);
      e=1;
    }
  }
}
Read More

Computing the Constant pi "π" in java

Problem:

You can computer π by using the following series seen below. Write a program that displays the value for  i 10000, 20000, and 100000.



Output:

For i = 10000 pi has a value of 3.1414926535900367
For i = 20000 pi has a value of 3.1415426535898203
For i = 30000 pi has a value of 3.1415593202564684
For i = 40000 pi has a value of 3.1415676535897927
For i = 50000 pi has a value of 3.141572653589808
For i = 60000 pi has a value of 3.1415759869231388
For i = 70000 pi has a value of 3.1415783678755265
For i = 80000 pi has a value of 3.1415801535898193
For i = 90000 pi has a value of 3.141581542478711
For i = 100000 pi has a value of 3.1415826535898224


Solution:

public class Pi
{
  public static void main (String[] args)
  {
    double n =0;
    for (int i =10000;i<=100000;i+=10000)
    {
      for (double j =1;j<=i;j+=2)
      {
        n+= ( ( 1.0/((2.0*j)-1.0) ) - ( 1.0/((2.0*j)+1.0) ) );
      }
      System.out.println("For i = " + i + " pi has a" +
          "value of " + (double) 4*n);
      
      n=0;
    }
  }
}
Read More

Calculating the Factors of a Number in Java

Problem:

Write a program that reads an integer and displays all its smallest factors in increasing order. For example, if the input integer is 120, the output should be as follows: 2, 2, 2, 3, 5.


Output:

1202 2 2 3 5


Solution:

public class Factors
{
  public static void main (String[] args)
  {
    java.util.Scanner scan = new java.util.Scanner(System.in);
    int N = scan.nextInt();
    for (int i =2;N>1;i++)
    {
      if(N%i == 0)
      {
        System.out.print(i +" ");
        
      N/=i;
      i=1;
      }
    }
  }
}
Read More

Printing The Four Basic Shapes in Java

Problem:

Print the shapes seen below.


Pattern I:


    int MAX = 5;
    for (int i =0;i<=MAX;i++)
    {
      for(int j =0;j<=i;j++)
      {
        System.out.print((j+1)+" ");
      }
      System.out.println();
    }


Pattern II:


    int MAX =5;
    for (int i =MAX;i>=0;i--)
    {
      for(int j =0;j<=i;j++)
      {
        System.out.print((j+1)+" ");
      }
      System.out.println();
    }


Pattern III:


    int MAX =5;    
    for (int i =MAX;i>=0;i--)
    {
      for(int j =0;j<i;j++)
      {
        System.out.print("  ");
      }
      
      for(int k =MAX;k>=i;k--)
      {
        System.out.print(k-i+1" ");
      }
      System.out.println();
    }


Pattern IV:

    int MAX = 6;
    for (int i =0;i<MAX;i++)
    {
      for (int j =0;j<i;j++)
      {
        System.out.print("  ");
      }
      
      for (int k =MAX;k>i;k--)
      {
        System.out.print(MAX-k+1+" ");
      }
      

      System.out.println();
    }



Read More

Using the Random Class in Java to Roll Dices

Problem:

Write an application that simulates the rolling of two dice. The application should use an object of a class Random once to roll the first die and again to roll the second die. The sum of the two values should then be calculated. Each die can show an integer value from 1 to 6. The sum of the values will vary from 2 to 12 with 7 being the most frequent sum, and 2 and 12 the less frequent sum. Your application should roll the dice 3600 times. Use one dimensional array to tally the number of times each possible sum appears. Display the result for example: 36 played that had the sum of 11.


Output:

101 played that had the sum of 2
179 played that had the sum of 3
305 played that had the sum of 4
437 played that had the sum of 5
515 played that had the sum of 6
606 played that had the sum of 7
493 played that had the sum of 8
377 played that had the sum of 9
303 played that had the sum of 10
182 played that had the sum of 11
102 played that had the sum of 12


Solution:

import java.util.Random;

public class Problem
{
  public static void main (String[] args)
  {
    Random d = new Random();
    int[] nums = new int[11];
    int a =0,b=0;
    for (int i =0;i<3600;i++)
    {
    a = d.nextInt(6) + 1;
    b = d.nextInt(6) + 1;
    switch(a+b)
    {
    case 2:
      nums[0]++;
      break;
    case 3:
      nums[1]++;
      break;
    case 4:
      nums[2]++;
      break;
    case 5:
      nums[3]++;
      break;
    case 6:
      nums[4]++;
      break;
    case 7:
      nums[5]++;
      break;
    case 8:
      nums[6]++;
      break;
    case 9:
      nums[7]++;
      break;
    case 10:
      nums[8]++;
      break;
    case 11:
      nums[9]++;
      break;
    case 12:
      nums[10]++;
      break;
    }

    }
    
    for (int i =0;i<11;i++)
      System.out.println(nums[i] + 
      " played that had the sum of " + (i+2));
  }
}
Read More

Calculating Gross Sales in Java

Problem:

Use a one-dimensional array to solve the following problem: A company pays its salespeople on a commission basis. The salespeople receive a $200 per week plus 9% of their gross sales for that week. For example, a salespeople who grosses 5000$ in sales in a week receives 200$ plus 9% of 5000$, or a total of 650$. Write an application (using an array of counters) that determines how many of the salespeople earned salaries in each of the following ranges(assume that each salesperson's salary is truncated to an integer amount):
Earned salaries:
$200-$299
$300-$399
$400-$499
$500-$599
$600-$699
$700-$799
$800-$899
$900-$999
$1000 and over
Summarize the results in tabular format


Output:

Earned salaries:        Gross sales:
$200-$299               $218-$226
$300-$399               $227-$235
$400-$499               $236-$244
$500-$599               $245-$253
$600-$699               $254-$262
$700-$799               $263-$271
$800-$899               $272-$280
$900-$999               $281-$289
$1000 and over          $290 and over


Solution:

public class Problem
{
  public static void main (String[] args)
  {
    int[] nums = new int[18];
    System.out.println("Earned salaries: " + "\t" +"Gross sales: ");
    int a = 200;
    for (int i =0; i <18; i+=2)
    {
      nums[i] = a; nums[i+1] = a+99;
      a+=100;
    }
    
    for (int i =0; i <18; i+=2)
    {
      if ( i == 16)
      System.out.println("$"+nums[i] +"" +" and over" +
                        "\t\t" +"$" + (int)(nums[i]*0.09 +200)+" "+"and over");
      else
      System.out.println("$"+nums[i] +"-" +"$" + nums[i+1]
                      +"\t\t" +"$" + (int)(nums[i]*0.09 +200)+"-"+"$" +
                                                    (int)(nums[i+1]*0.09 +200));

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