class PrimeNo {
public static void main(String[] args) {
int n = 8;// assumed to be any random number
int i;
if (n == 0 || n == 1)
System.out.println("Not a prime number");
else {
for (i = 3; i < n; i++) {
if (n % i == 0) {
System.out.println("Not a prime number");
} else {
System.out.println("Prime number");
}
break;
}
}
}
}
I have written a basic code to find a given number is Prime number or not? I tried this by not using flags. Let we assume "n" to be any number. When I run the code it prints both "Prime" and "Not Prime" in different lines. Also, why is this code a dead code? If we go through logic this code should have runned perfectly. Help me out guys!!!
Your break is the culprit, it will break at first iteration, i will never get incremented and hence dead code.
I have written a basic code to find a given number is Prime number or
not? I tried this by not using flags.
Given below is how you can do it without using a flag:
public class Main {
public static void main(String[] args) {
int n = 8;// assumed to be any random number
int i;
if (n == 0 || n == 1)
System.out.println("Not a prime number");
else {
for (i = 2; i < n; i++) {
if (n % i == 0) {
System.out.println("Not a prime number");
break;
}
}
// If n % i == 0 doesn't become true throughout the loop, it means n is prime
if (i == n) {
System.out.println("Prime number");
}
}
}
}
Output:
Not a prime number
Note that I have started the loop from 2 which is also a prime number.
Another important thing to consider is that you do not need to divide and check until n (i.e. i < n), checking till the square root of n is sufficient. Check this to learn more about it. Thus, an efficient way of doing it as follows:
public class Main {
public static void main(String[] args) {
int n = 8;// assumed to be any random number
int i, sqrt = (int) Math.sqrt(n);
if (n == 0 || n == 1)
System.out.println("Not a prime number");
else {
for (i = 2; i <= sqrt; i++) {
if (n % i == 0) {
System.out.println("Not a prime number");
break;
}
}
// If n % i == 0 doesn't become true throughout the loop, it means n is prime
if (i > sqrt) {
System.out.println("Prime number");
}
}
}
}
Output:
Not a prime number
Also, why is this code a dead code?
When your loop runs for i = 3, it will be terminated by break; statement. This, i++ will never get a chance to run and thus, it is a dead code.
Since you are using 'break;' in your code, for loop was running only once. This means the 'i++' part in your for loop was never been called and hence the dead code error.
You might want to write your logic something similar to this:
class PrimeNo {
public static void main(String[] args) {
int n = 8;// assumed to be any random number
int i;
boolean isNumberPrime = true;
if (n == 0 || n == 1)
isNumberPrime = false;
for (i = 2; i < n; i++) {
if (n % i == 0) {
isNumberPrime = false;
}
}
if (isNumberPrime) {
System.out.println("Number is prime number");
} else {
System.out.println("Number is not prime number");
}
}
}
Sorry I missed the no flag part. We could implement the code as below with no flags:
class PrimeNo {
public static void main(String[] args) {
int n = 8; // assumed to be any random number
int i;
if (n == 0 || n == 1)
System.out.println("Number is not prime number");
for (i = 2; n > 1 && i < n; i++) {
if (n % i == 0) {
System.out.println("Number is not prime number");
break;
} else if (i == n - 1) {
System.out.println("Number is prime number");
}
}
}
}
Related
This is my first question on StackOverflow so please pardon any mistakes but let me know about them. I am trying to do problem 5 on Project Euler in Java. I feel like my code is correct but I can not get the answer.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
public class Main {
public static void main(String[] args) {
boolean a = true;
int counter = 0;
int b = 1;
while (a) {
for (int i = 1; i <= 20; i++) {
if (b % i == 0) {
counter++;
}
if (counter == 20) {
System.out.println(b);
a = false;
}
else {
b++;
}
counter = 0;
}
}
}
}
The problem is that your nesting is wrong.
Within the for (int i = 1; i <= 20; i++) loop you increment counter if b is divisible by i.
The you do some checks and in the end set counter to zero again.
That means that your counter only ever reaches a maximum value of 1 (if b is divisible by a specific i).
You probably meant to write
for (int i = 1; i <= 20; i++) {
if (b % i == 0) {
counter++;
}
}
if (counter == 20) {
System.out.println(b);
a = false;
}
else {
b++;
}
counter = 0;
which will give the correct result - although the algorithm is still terribly slow.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
This post was edited and submitted for review last year and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
(1) Original question with problematic solution:
This question is checking the number is prime or not.
public static void main(String[] args) {
input = new Scanner(System.in);
System.out.println("Enter a prime number ( you think ) : ");
int num = input.nextInt();
isPrime = false;
for(int divisor = 2; divisor < num / 2; divisor++) {
if(num % divisor == 0){
isPrime = false;
}
isPrime = true;
}
if(isPrime) {
System.out.println("Prime");
}
else {
System.out.println("Not a prime");
}
}
(2) ###Updated:
The main reason is not working is the flag caused the issue: isPrime = true;
isPrime = false;
for(int divisor = 2; divisor < num / 2; divisor++) {
if(num % divisor == 0)
{
isPrime = false;
}
isPrime = true; // May 2020: no matter what num, it will become true here.
}
(3) ###Updated: The working solution with a method:
class Prime {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter a prime number ( you think ) : ");
int num = input.nextInt();
if(ifPrime(num)) {
System.out.println(num + " is a prime number");
}
else {
System.out.println(num + " is a NOT prime number");
}
}
private static boolean ifPrime(int num) {
for(int divisor = 2; divisor < num; divisor++) {
if( num != divisor && num % divisor == 0){
return false;
}
}
return true;
}
}
The main issue here is that you overwrite the value of isPrime in every iteration, so if the last divisor you check does not divide num, you interpret it as a prime.
A better approach would be to assume a number is a prime until proven otherwise (i.e., until you find a divisor for it). Once you've found such a divisor, you can break out of the loop - the number isn't a prime, and there's no reason to keep on checking it:
isPrime = true;
for(int divisor = 2; divisor <= num / 2; divisor++) {
if (num % divisor == 0) {
isPrime = false;
break; // num is not a prime, no reason to continue checking
}
}
In your code
for(int divisor = 2; divisor < num / 2; divisor++) {
if(num % divisor == 0)
{
isPrime = false;
}
isPrime = true;
}
If isPrime = false, then you make it true again!
You can consider this:
isPrime = true;
for(int divisor = 2; divisor < num / 2; divisor++) {
if(num % divisor == 0)
{
isPrime = false;
break;
}
}
Try with this:
public class prime{
public static void main (String args[]){
int n1=100, n2=1000;
int c=0;
for(int i=n1; i<=n2; i++)
if(isPrime(i)==true)
c++;
System.out.print(c);
}
public static boolean isPrime(int number)
{
for(int j=2; j<number; j++) //u go from number+1 to number to check
//if it can be divided by any other value.
if(number % j ==0) //if there is 1 other number that divides it then
//it returns false.
return false;
return true; //else it returns true.
}
}
public class PrimeNum {
private static boolean isPrime;
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
System.out.println("Enter a number ( you think ) : ");
String ch = input.next();
if (isNumeric(ch)) {
int num = Integer.parseInt(ch);
isPrime = true;
if (num > 1) {
for (int divisor = 2; divisor * divisor <= num; divisor++) {
if (num % divisor == 0) {
isPrime = false;
break;
}
}
} else {
isPrime = false;
}
if (isPrime) {
System.out.println("Prime");
} else {
System.out.println("Not a prime");
}
} else {
System.out.println("Should input a number");
}
}
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*|\\-[0-9]*");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
}
I'm doing the program for SPOJ.com taks which should recognize Prime number. Unfortunately this SPOJ taks is in Polish language, hence I will try to translate what should be the input and outpu expectation:
Input:
n - the number of tests n <100000, in the next lines n numbers from the interval [1..10000]
Output:
For each number of the word "YES", if this number is prime. Word: "NO", otherwise.
Example:
Input:
3
11
1
4
Output:
YES
YES
NO
I wrote following code whcih during the test works perfectly fine. Unfortunately when I'm trying to submit this code on SPOJ webpage it is constantly returning me error "
runtime error (NZEC)" Can someone advise how I can improve it?
Scanner in = new Scanner(System.in);
int n = in.nextInt();
if(1<=n&& n<=100000){
for(int i = 0; i<n+1; i++){
int v = in.nextInt();
if(1<=v&&v<=10000){
if(isPrime(v) == true){
System.out.println("YES");
}
if(isPrime(v) == false){
System.out.println("NO");
}
}
}
}
}
private static boolean isPrime(int v) {
if (v < 2) return true;
if (v == 2) return true;
if (v % 2 == 0) return false;
for (int i = 3; i * i <= v; i += 2)
if (v % i == 0) return false;
return true;
}
Have you learnt Sieve Method for Prime numbers.
Check here you will find the better solution.
public class PrimeSieve {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
// initially assume all integers are prime
boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) {
isPrime[i] = true;
}
// mark non-primes <= n using Sieve of Eratosthenes
for (int factor = 2; factor*factor <= n; factor++) {
// if factor is prime, then mark multiples of factor as nonprime
// suffices to consider mutiples factor, factor+1, ..., n/factor
if (isPrime[factor]) {
for (int j = factor; factor*j <= n; j++) {
isPrime[factor*j] = false;
}
}
}
// count primes
int primes = 0;
for (int i = 2; i <= n; i++) {
if (isPrime[n]) primes++;
}
System.out.println("The number of primes <= " + n + " is " + primes);
}
}
You should check all numbers from 2 to n, to see if the number isPrime or not.
Code
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i = 0; i < n ; i++) {
int v = in.nextInt();
if (v >= 1 && v < 10000) {
if (isPrime(v) == true) {
System.out.println("YES");
}
if (isPrime(v) == false) {
System.out.println("NO");
}
}
}
}
private static boolean isPrime(int v) {
for(int i=2;i<v;i++) {
if(v%i==0)
return false;
}
return true;
}
}
I hope this helps you.
I'm not sure why my ct is not going all the way to 100 even though I clearly set it to go until it reaches 100.
public class PalindromicPrime
{
public static void main(String [] args)
{
int ct = 0;
while(ct < 100)
{
if(isPalindrome(ct) && isPrime(ct))
{
if(ct % 10 != 0)
{
System.out.print(ct + " ");
}
else
{
System.out.print("\n");
}
}
ct++;
}
public static boolean isPalindrome(int p)
{
int palindrome = p;
int reverse = 0;
while (palindrome != 0)
{
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
if (p == reverse)
{
return true;
}
return false;
}
I'm assuming my isPrime code is wrong since I'm getting a 4 in my output. What's wrong with this method?
public static boolean isPrime(int p)
{
for(int i = 2; i < p/2; i++)
{
if(p % i == 0)
{
return false;
}
}
return true;
}
}
First change you should do in your method isPrime() is change this line
for(int i = 2; i < p/2; i++)
to
for(int i = 2; i <= p/2; i++) // you can easily find the reason why it is necessary(=)
And also you are printing palindromic numbers less than 100 which are prime,not first 100 palindrome numbers, if you want to print first 100 palindrome numbers you can take another counter which will keep track of the numbers printed.
You can modify your main method like this:
public static void main(String [] args)
{
int ct = 0,n=0; // n to count numbers printed/found
while(n < 100) // change the condition to check n<100
{
if(isPalindrome(ct) && isPrime(ct))
{
System.out.print(ct + " ");
if(n % 10 == 0)
{
System.out.println();
}
n++; // incementing n after a number is found!
}
ct++;
}
}
Your palindrome method is fine. It's your isPrime method that's not working because to check if a number is prime, you're supposed to test factors up to the square root of the number. So a simple change in the condition should do it,
public static boolean isPrime(int p)
{
for(int i = 2; i <= Math.sqrt(p); i++)
{
if(p % i == 0)
{
return false;
}
}
return true;
}
}
Change your isPrime function to following (replace < with <= as 4/2 is 2 and loop will not run at all for p=4):
public static boolean isPrime(int p) {
for (int i = 2; i <= p / 2; i++) {
if (p % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int ct = 2;
int count = -1;
while (count < 99) {
if (isPalindrome(ct) && isPrime(ct)) {
count++;
if (count % 10 == 0) {
System.out.print("\n" );
}
System.out.print(ct + " ");
}
ct++;
}
}
The only numbers that are palindrome and prime and less than 100 are:
1 2 3 5 7 11
Try changing the value of 100 to 102. Then you get the following output as 101 is the next palindromic prime after 11:
1 2 3 5 7 11 101
I'm having some trouble in completing this factor generator from my programming class. It's supposed to take a number, and print out all the factors using the nextFactor method. When I set the number to factor to let's say 150, it prints out "1 2 3 5", where it's supposed to print "2 3 5 5". So, where should I go from here? I've looked at Java - Factor Generator program nextfactor method, but it didn't awnser any of my inqueries
public class FactorGenerator
{
//user inputs int from scanner in FactorTester class
public FactorGenerator(int i)
{
num = i;
}
//Checks to see if num can be factored, but does not factor it.
//Goes through all possible factors of num and returns true if the remainder == 0
public boolean hasMoreFactors()
{
for(int i = 1; i < num; i++)
{
//check if the remainder is anything other then 0
if(num % i == 0)
{
return true;
}
}
return false;
}
//Actually factors num and prints out the factor at the end of every loop.
public void nextFactor()
{
for(int i = 1; i < num; i++)
{
//check if the remainder is anything other then 0
if(num % i == 0)
{
System.out.println(i);
num /= i;
}
}
System.out.println("Done.");
}
private int num;
}
try this factors can duplicate so you need to loop until you have extracted all the instances of that factor
public void nextFactor()
{
for(int i = 2; i <= num; i++)
{
//check if the remainder is anything other then 0
while (num >= i && num % i == 0)
{
System.out.println(i);
num /= i;
}
}
System.out.println("Done.");
}
an alternative way is to do the increment in the body of the loop
public void nextFactor()
{
for(int i = 2; i <= num;)
{
//check if the remainder is anything other then 0
if (num % i == 0)
{
System.out.println(i);
num /= i;
} else {
i++;
}
}
System.out.println("Done.");
}
For starters, it will always print out 1 because any integer / 1 will always have remainder of zero. You can start i from 2 instead of 1 in your for if you want to skip 1.
I'd suggest something like this: (note this is based in part on BevynQ's answer below):
for(int i = 2; i <= num; i++){
while (num >= i && num % i == 0) {
System.out.println(i);
num /= i;
}
}