Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class IsPrime
- {
- //determine if a given integer is prime
- public static void main(String[] args)
- {
- //declare variables
- Scanner input = new Scanner(System.in);
- int num, i;
- double quotient;
- boolean isPrime = true;
- //take integer
- System.out.print("Enter an integer: ");
- num = input.nextInt();
- /*
- * --test if prime--
- * -iterate through every int in range 1 <= i <= num
- * -divide num by i
- * -if result is a non-integer, number is not prime, break loop
- * -if the loop exits without breaking, number is prime
- */
- for (i = num; i > 0; i--)
- {
- quotient = (double)num / (double)i;
- if (quotient != (int)quotient)
- {
- isPrime = false;
- break;
- }
- }
- //print result
- if (isPrime)
- {
- System.out.printf("%d is prime.\n", num);
- }
- else
- {
- System.out.printf("%d is not prime.\n", num);
- }
- //clean up
- input.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement