/*Ok I have code that's behaving unexpectedly
The following program is supposed to print prime numbers for n1=100,n2=1000,n3=10000 and n4=100000 except that for n1=100, it prints the squares of primes less than 10. I can implement this same program in c++ and wouldn't get such output. I need another pair of eyes to look through my code and tell me if there's anything semantically wrong with it. Thanks */

import java.util.*;
import java.lang.*;
class Rextester
    public static void main(String args[])
    int n1=100;int n2=1000;int n3=10000;int n4=100000;
    long start = System.nanoTime();
    int n=0;
        for(int i=2;i<n1;i++){
            for(int j=2;j<i;j++){
     long end = System.nanoTime();
     System.out.println("The execution time was: "+(end-start)+" nanoseconds.");
Re: Why does my program print squares of numbers 80 80

Seems to me that this won't work in either C++ or Java due to Algorithm problems. Take i = 2 for example. That's prime, but according to your code it isn't. n is set as 0 before the j loop. The j loop from 2 to (i-1). In this case, i is 2, so i-1 is 1. Hence the j loop will execute 0 times, so n remains 0. n is prime according to your code if and only if n is 1. Hence 2 is not prime.

Seems to me that the number should be prime if n is equal to 0, not 1?

Wait a minute, now I am confused...

it prints the squares of primes less than 10

Line 17.

System.out.println(i); // no squaring.

The program is SUPPOSED to print out all primes less than 100, correct?

[EDIT 2]
OK, I get it now, I think. It makes sense that it would print the squares of primes. It doesn't catch the primes, for the reason listed above. It will catch a number like 25, though, which is 5 squared. When i is 25 and j is 5, 25 % 5 is 0, hence n is incremented. Since 5 times 5 is the ONLY factor of 25, n will be 1 according to your code. Test for n equal to 0, not 1, and see if the program works. Again, I don't see this as a C++ versus Java issue. You should get the same result in either language as far as I can tell.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.