Advertisement
TheFastFish

IsPrime

Nov 20th, 2015
664
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.95 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class IsPrime
  4. {
  5.     //determine if a given integer is prime
  6.     public static void main(String[] args)
  7.     {
  8.         //declare variables
  9.         Scanner input = new Scanner(System.in);
  10.         int num, i;
  11.         double quotient;
  12.         boolean isPrime = true;
  13.        
  14.         //take integer
  15.         System.out.print("Enter an integer: ");
  16.         num = input.nextInt();
  17.        
  18.         /*
  19.          * --test if prime--
  20.          * -iterate through every int in range 1 <= i <= num
  21.          * -divide num by i
  22.          * -if result is a non-integer, number is not prime, break loop
  23.          * -if the loop exits without breaking, number is prime
  24.          */
  25.         for (i = num; i > 0; i--)
  26.         {
  27.             quotient = (double)num / (double)i;
  28.             if (quotient != (int)quotient)
  29.             {
  30.                 isPrime = false;
  31.                 break;
  32.             }
  33.         }
  34.        
  35.         //print result
  36.         if (isPrime)
  37.         {
  38.             System.out.printf("%d is prime.\n", num);
  39.         }
  40.         else
  41.         {
  42.             System.out.printf("%d is not prime.\n", num);
  43.         }
  44.        
  45.         //clean up
  46.         input.close();
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement