Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

I've been working on this code to check whether no is prime or not the problem is i cannot understand syntax plz help

I am using this code to find whether a no is prime or not the problem is in the for loop i cannot understand why we need to us this condn statment (i<=num/i). Please i don't have problem in syntax i have problem in understanding how the loop works just (i<=num/i) condn. ****/******* package javalearning; // This code tries to check the whether no is prime or not by divinding it with 2 3 4 and so on .. until the the divisor is less then or equal to the dividend/divisor import java.util.Scanner; public class forDemo {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner input=new Scanner(System.in);
    int num=input.nextInt();
    boolean isPrime=false;
    // this code is to illustrates prime no test using for loop
    for (int i=2; i<=num;i++)
    {
        if (num%i==0 ) {isPrime=false; break;}
        else isPrime=true;
    }
    System.out.println("IS YOUR NO A PRIME : "+isPrime);
}

} /************/************** Plese forgive me for using long line of codes. Thanks for help

1 Answer

Jefferson Duong
seal-mask
.a{fill-rule:evenodd;}techdegree
Jefferson Duong
Full Stack JavaScript Techdegree Student 4,763 Points

I believe the problem lies within your for loop. Remove the = from the i<=num and you should be good!

The reason is that with the = there, it will always go to that number and be % = 0. Example: if you input 23, which is a prime number, it'll go through that entire loop and won't be divisible(like it should) but then it'll go all the way to 23 (which it shouldn't).

Recap: just make it for (int i=2; i<num;i++) and you're good! Great job!