Prime code error

import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int d=2;
while(d<=n){
if(n%d==0){
System.out.println(“Not Prime”);
return;
}
else{
System.out.println(“Prime”);
return;
}
}

}

}
working fine in eclipse compiler.
error generated is EXCEPTION IN THREAD"MAIN" .what to change

Hii,
Increase the value of d by 1 inside the while loop. As you dont increase the value of d, the value of d remains 2 and thus the while loop become infinite loop.

import java.util.*; public class Main { public static void main(String args[]) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int d=2; while(d<=n){ if(n%d==0){ System.out.println(“Not Prime”); return; } else{ System.out.println(“Prime”); return; d++; } } } }

what changes are needed now

import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int d=2;
while(d<=n-1)
{
if(n%d==0)
{
System.out.println(“Not Prime”);
return;
}
d++;
}
if(n==d)
System.out.println(“Prime”);
} }
this is the correct answer…

d++ that you wrote couldn’t be reached as since u used both if and else statement inside the while loop with return statement in it.Whenever the condition didn’t meet it eventually went to else block and the d thing is never incremented and we get a wrong answer. the condition you applied was also wrong because we are dividing the number from 2 to n-1 since a number is said to be prime if it is divisible by 1 and itself. So we need not to divide the number by itself

import java.util.*; public class Main { public static void main(String args[]) { Scanner s=new Scanner(System.in); int n=s.nextInt(); for(int d=2;d<=n;d++){ if(n%d==0){ System.out.println(“Not Prime”); return; } else{ System.out.println(“Prime”); return; } } } } whats wrong

1.Condition is wrong. Correction : d<=n-1
2.If the condition for the if block to be executed is not met then else block will be executed and d will never be incremented and you will get a wrong answer.

import java.util.*; public class Main { public static void main(String args[]) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int d=2; while(d<=n-1){ if(n%d==0){ System.out.println(“Not Prime”); return; } d++; } if(n==d) System.out.println(“Prime”); }}

stll not working run error (Time o s ) please help

please resolve. i have tried multiple times now

Hi Ritu, can you please copy your code on cb.lk/ide, save it and share that link here.

Hey Ritu,
As you are not responding to this thread, I am marking your doubt as Resolved for now. Re-open it if required.

Please mark your doubts as resolved in your course’s “ Ask Doubt ” section, when your doubt is resolved.