Computer Science
A Circular Prime is a prime number that remains prime under cyclic shifts of its digits. When the leftmost digit is removed and replaced at the end of the remaining string of digits, the generated number is still prime. The process is repeated until the original number is reached again.
A number is said to be prime if it has only two factors 1 and itself.
Example:
131
311
113
Hence, 131 is a circular prime.
Accept a positive number N and check whether it is a circular prime or not. The new numbers formed after the shifting of the digits should also be displayed.
Test your program with the following data and some random data:
Example 1
INPUT:
N = 197
OUTPUT:
197
971
719
197 IS A CIRCULAR PRIME.
Example 2
INPUT:
N = 1193
OUTPUT:
1193
1931
9311
3119
1193 IS A CIRCULAR PRIME.
Example 3
INPUT:
N = 29
OUTPUT:
29
92
29 IS NOT A CIRCULAR PRIME.
Java
Java Iterative Stmts
ICSE Prac 2016
37 Likes
Answer
import java.util.Scanner;
public class CircularPrime
{
public static boolean isPrime(int num) {
int c = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
c++;
}
}
return c == 2;
}
public static int getDigitCount(int num) {
int c = 0;
while (num != 0) {
c++;
num /= 10;
}
return c;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("ENTER INTEGER TO CHECK (N): ");
int n = in.nextInt();
if (n <= 0) {
System.out.println("INVALID INPUT");
return;
}
boolean isCircularPrime = true;
if (isPrime(n)) {
System.out.println(n);
int digitCount = getDigitCount(n);
int divisor = (int)(Math.pow(10, digitCount - 1));
int n2 = n;
for (int i = 1; i < digitCount; i++) {
int t1 = n2 / divisor;
int t2 = n2 % divisor;
n2 = t2 * 10 + t1;
System.out.println(n2);
if (!isPrime(n2)) {
isCircularPrime = false;
break;
}
}
}
else {
isCircularPrime = false;
}
if (isCircularPrime) {
System.out.println(n + " IS A CIRCULAR PRIME.");
}
else {
System.out.println(n + " IS NOT A CIRCULAR PRIME.");
}
}
}
Output



Answered By
6 Likes
Related Questions
How many times will the following loop execute? Write the output of the code:
int a = 5; while (a > 0) { System.out.println(a-- + 2); if (a % 3 == 0) break; }
To execute a loop 10 times, which of the following is correct?
- for (int i=11;i<=30;i+=2)
- for (int i=11;i<=30;i+=3)
- for (int i=11;i<20;i++)
- for (int i=11;i<=21;i++)
Convert the following for loop segment to an exit-controlled loop.
for (int x = 1, y = 2; x < 11; x += 2, y += 2) { System.out.println(x + "\t" + y); }
Write a program to input a number and find whether the number is an emirp number or not. A number is said to be emirp if the original number and the reversed number both are prime numbers.
For example, 17 is an emirp number as 17 and its reverse 71 are both prime numbers.