2 Replies - 205 Views - Last Post: 08 October 2012 - 03:06 PM Rate Topic: -----

#1 kamikazeren  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 07-October 12

noob question about prime loops

Posted 08 October 2012 - 12:01 AM

Sorry about bothering you guys but I can't seem to understand a certain portion of code.


System.out.print("enter an integer greater than 2: ");
int n = reader.nextInt();

int count = 0;
int limit = n/2;

for (int d= 2; d <= limit; d++) {
       if (n % d == 0)
        count ++; // I got confused here as to the count's purpose
}
if (count != 0)
System.out.println("Not prime");
else
System.out.println("prime");




Can some please explain the function of the count in there? It confuses me.

Is This A Good Question/Topic? 0
  • +

Replies To: noob question about prime loops

#2 raghav.naganathan  Icon User is offline

  • Perfectly Squared ;)
  • member icon

Reputation: 408
  • View blog
  • Posts: 1,440
  • Joined: 14-September 12

Re: noob question about prime loops

Posted 08 October 2012 - 12:10 AM

View Postkamikazeren, on 08 October 2012 - 12:31 PM, said:

Sorry about bothering you guys but I can't seem to understand a certain portion of code.


System.out.print("enter an integer greater than 2: ");
int n = reader.nextInt();

int count = 0;
int limit = n/2;

for (int d= 2; d <= limit; d++) {
       if (n % d == 0)
        count ++; // I got confused here as to the count's purpose
}
if (count != 0)
System.out.println("Not prime");
else
System.out.println("prime");




Can some please explain the function of the count in there? It confuses me.


What count does basically is increments the counter for your finding whether number is composite or prime.

say you took n as 4, so 4%2=0 and count will increment by 1 , therefore, when the control exits for loop, count has the value of 1 and so, it will print " not prime".

Suppose you took d as 5 , 5%2 will never yield 0 as answer so count value will never be incremented. When control exits for loop, as count value is 0, it will print "prime". :)

regards,
Raghav

This post has been edited by raghav.naganathan: 08 October 2012 - 12:11 AM

Was This Post Helpful? 0
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8334
  • View blog
  • Posts: 31,858
  • Joined: 06-March 08

Re: noob question about prime loops

Posted 08 October 2012 - 03:06 PM

I would get confused too :)
Counting the even bnumber in a loop is really inefficient
just divide the loop range by 2 and you should have what you want...
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1