Why is this if-condition always excluding 2? - java

I created this loop to find prime numbers, the int num is initialized as 0, but the debugger always skips 1 (which is correct) and 2 (which is not correct).
How does it come that it always skips 2 % 2 == 0 ?
for (int num = 0; num <= 100; num++) {
for (int j = 2; j < num; j++) {
if (num % j == 0) {
System.out.println(num + " is not a prime number.");
break;
}
if (num - j == 1) {
System.out.println("PRIME NUMBER FOUND! It's: " + num + ".");
myPrimeNumbers.add(num);
}
}
}

The problem with your code is that in the case num=2 you don't get into the part where you add the prime number. You chose to use the last iteration of the inner loop as the place where to add a prime number to your list, but with num=2 the inner loop has 0 iterations.
I'd modify your program as follows:
package test;
import java.util.ArrayList;
import java.util.List;
public class Test {
private static boolean isPrime(int num) {
for (int j = 2; j < num; j++) {
if (num % j == 0) {
return false;
}
}
return true;
}
public static void main (String [] args) {
List<Integer> myPrimeNumbers = new ArrayList<>();
for (int num = 2; num <= 100; num++) {
if (isPrime(num)) {
System.out.println("PRIME NUMBER FOUND! It's: " + num + ".");
myPrimeNumbers.add(num);
}
}
}
}
Extracting the prime test into a method makes it easy to place the true and false returns at locations where they are intuitively correct.
And I started the prime number search with 2 instead of 0 as we all know that 0 and 1 are by definition no primes.

Related

why do we use < and not <= in second loop while printing prime numbers

Below is the code snipent
first loop contains numbers from 1 to 100 and second loop to iterate through numbers , in second loop if we use <= prime numbers are not getting printed
public class primeNumbers {
public static void main(String args[]) {
int i, number, count;
System.out.println("Prime Numbers from 1 to 100 are : ");
for (number = 1; number <= 100; number++) {
count = 0;
for (i = 2; i <= number; i++) {
if (number % i == 0) {
count++;
break;
}
}
if (count == 0 && number != 1) {
System.out.print(number + " ");
}
}
}
}
We know that
Every natural number has both 1 and itself as a divisor. If it has any other divisor, it cannot be prime.
from https://en.wikipedia.org/wiki/Prime_number.
In addition to this, it is only necessary to loop from 2 until the square root of the number you are testing (explained here).
This way we can write the second loop as:
for (i = 2; i <= Math.sqrt(number); i++) {
It is only necessary to discover if there is any natural number that is a divisor of number between 2 and Math.sqrt(number) - inclusively. If this is the case, number is not a prime. Otherwise it is a prime.
E.g.: Let's see the case where number = 4. We already know that the number 4 has 1 and itself (4) as divisors. So, we want to loop from 2 to Math.sqrt(4) = 2 to discover if there are any more divisors. And in this case in the first iteration where i = 2, we find that (4 % 2) == 0. So 4 is not prime.
This would be written like this:
public static void main(String[] args) {
System.out.println("Prime Numbers from 1 to 100 are:");
for (int number = 2; number <= 100; number++) {
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(number + " ");
}
}
}
prime numbers are divisible by 1 and itself. The second loop run from 2, which means that when you check one number is divisible by itself, that does not make sense. using " < " is optimise

Program that displays every perfect number

My code runs but for one of the tests two outputs are printed when I only need one. I am unsure of how to avoid this.
This is the task:
Write an application that displays every perfect number from 2 through 1,000. A perfect number is one that equals the sum of all the numbers that divide evenly into it. For example, 6 is perfect because 1, 2, and 3 divide evenly into it and their sum is 6; however, 12 is not a perfect number because 1, 2, 3, 4, and 6 divide evenly into it, and their sum is greater than 12.
The provided template lays out the initial for loop to check each number beginning from 2 and going up to 1,000. In this for loop, the perfect() method is called, where you will submit your piece of code to test if each number follows the conditions described above.
Set result to true if it meets those conditions and use sum to add up the numbers divisible by int n in the method's parameter.
public class Perfect{
public static void main (String args[]){
final int MAX = 1000;
for(int i = 2; i <= MAX; i++)
if(perfect(i) == true)
System.out.println("The number " + i + " is perfect");
}
public static boolean perfect(int n){
int sum = 1;
int i;
boolean result = false;
for (i = 2; i < n / 2; i++) {
if (n % i == 0) {
sum += i;
}
}
if (sum == i) {
return true;
}
else {
return false;
}
}
}
My output:
The number 496 is perfect
The number 729 is perfect
Expected output:
The number 496 is perfect
It only expects the first line printed...
You need to compare sum to the original number n, not to i. And you need to add 1 to the loop condition or it will miss the last divider in even numbers
public static boolean perfect(int n){
int sum = 1;
for (int i = 2; i < (n / 2) + 1; i++) {
if (n % i == 0) {
sum += i;
}
}
return sum == n;
}
First, I don't know if you have used the correct formula. But, you should know that the first perfect number are 6, 28, 496 and 8128. 729 is not a perfect number.
Hope it helped.
public static void main(String[] args) {
int i, j, s;
System.out.println("Perfect numbers 1 to 1000: ");
for(i=1;i<=1000;i++){
s=0;
for(j=1;j<i;j++){
if(i%j==0){
s=s+j;
}
}
if(i==s){ //if i == s is perfect
System.out.println(i);
}
}
}
}
According to the question, you have to print all perfect numbers.
I have created a small snippet, try it and see.
public void printPerfect() {
for(int i=2;i<1000;i++) {
List<Integer> l =factors(i);
int sum =0;
for (Integer factor : l) {
sum+=factor;
}
if(sum==i) {
System.out.println("perfect-- " +i);
}
}
}
List<Integer> factors(int number) {
List<Integer> l = new ArrayList<Integer>();
for(int i = 1; i <= number; ++i) {
if (number % i == 0) {
if(i!=number)
l.add(i);
}
}
return l;
}
You checked sum == i instead of sum == n.
As 729 = 3^6 : 3, 243, 9, 81, 27.
public static boolean perfect(int n) {
int sum = 1;
for (int i = 2; i <= n / 2 && sum <= n; i++) {
if (n % i == 0) {
sum += i;
}
}
return sum == n;
}

Why does my prime number java program not print out prime numbers?

static void primeNumbers(int n)
{
System.out.println("All the prime numbers up to "+n+" are -->\n");
boolean isPrime = true;
for(int i = 2; i < n; i++)
{
for (int j = 1; j < i; j++)
{
if(i % j == 1)
{
isPrime = true;
System.out.print(j);
}
if(i % j == 0)
{
isPrime = false;
System.out.print(" ");
}
}
}
}
In this code I am trying to list all the prime numbers up to 'n' which is the number the user inputs. I am confused as to how to fix this to produce all of the prime numbers up to n.
You want to test if i is dividable by any number in the range of [2..i-1] and if it is, then it is not a prime number. Your j-loop starts at 1, that is the first error.
Knowing when a number is dividable by another is tested like this: if (i % j == 0) { (if the division remainder is zero) where in your code you test for equality with 1 instead.
Third thing is that you make your decision in the first iteration (when j is 1) and always print something in your inner loop. You need to take the logic out of the inner loop. Only if i is not dividable by any of the js then it is prime.
Here is a modified version of your code:
static void primeNumbers(int n) {
System.out.println("All the prime numbers up to "+n+" are -->\n");
for (int i = 2; i < n; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if(i % j != 0) {
isPrime = false;
}
}
if (isPrime) {
System.out.print(i, " ");
}
}
}
if (i % j == 0) {
isPrime = false;
System.out.print(" ");
}
This if statement is always true for any i because j starts at 1. As a result, you print a space for every number < n and >= 2
Also, isPrime may be an unnecessary variable.
Your algorithm, although slow, seems to be correct on most parts except for the fact that you are not handling the boundary conditions well. E.g. 2 is a prime number, you are running iterations only till n-1, you are not reseting the isPrime flag for every number, and a few small things. Here's a revised working version. Try to compare it with yours and understand where you didn't get it right.
int n = 10;
System.out.println("All the prime numbers up to "+n+" are -->\n");
boolean isPrime = true;
for(int i = 2; i <= n; i++)
{
for (int j = 2; j < i; j++)
{
if(i % j == 0)
{
isPrime = false;
break;
}
}
if(isPrime) {
System.out.println(i);
}
isPrime = true;
}
Don't re-set isPrime to true in your second for loop, as soon as the number is not prime once, we know it is not prime forever. Just set it to true once every iteration of the outer loop, and do your final "Is prime" check outside.
static void isPrime(int n)
{
System.out.println("All the prime numbers up to "+n+" are -->\n");
for(int i = 2; i <= n; i++)
{
boolean isPrime = true;
for (int j = 2; j < i; j++)
{
if(i % j == 0)
{
isPrime = false;
System.out.println(i + " is not prime because " + i + " is divisible by " + j );
break;
}
}
if (isPrime){
System.out.println(i + " is prime.");
}
}
}
I've added a couple prints to this code so that you can see why each part of the logic is doing what it does -- compare it to your code so that you can understand why yours doesn't actually search for primes.
I think is a logical problem in your script.
You should count with a loop all the number from 2 to n-1 which are = to 0 with a test
n%i = 0
If the counter = 0 then no divider then prime number

Prime number program does not work

I am trying to make a simple program in Java that would output all the prime numbers (skipping number 2) up to the number n. It doesn't work and I am out of ideas. If someone could take a look at my code and tell me what the problem is I would greatly appreciate it.
public class PrimeNum {
public static void main(String[] args) {
int n = 50;
int notAPrime = 0;
System.out.println("All prime numbers before number " +n+ " are : ");
for(int i = n; i > 2; i--){
for(int j = 2; j < i; j++){
if(i % j == 0){
notAPrime++;
}
}
if(notAPrime == 0){
System.out.println(i);
notAPrime = 0;
}
}
}
}
Just declare notAPrime inside for(int i = n; i > 2; i--) to make it local for each i - candidate to be prime.
Now you increase notAPrime and never reset it to zero.
try this
public class primeNum {
public static void main(String[] args) {
int n = 50;
boolean prime;
System.out.println("All prime numbers before number " +n+ " are : ");
for(int i = n; i > 2; i--){
prime = true;
for(int j = 2; j < i; j++){
if(i % j == 0){
prime = false;
}
}
if(prime){
System.out.println(i);
}
}
}
}
note, that i changed your "notAPrime" variable from int into boolean and into a name that tells you what it means. if you only increment the "notAPrime" integer, you will never get any desired outcome.
By the way, this wa a hotfix and you got a corrected first form of your code. Have in mind, that 2 is a prime number aswell and your code ignores this.
Just work a little mor on it ;)
You are missing a "break" in your for loop.
public class primeNum {
public static void main(String[] args) {
int n=50;
int notAPrime=0;
System.out.println("All prime numbers before number " +n+ " are : ");
for(int i=n; i>2; i--){
for(int j=2; j<i; j++){
if(i%j==0){
notAPrime++;
break; //your program is missing this statement
}
}
if(notAPrime==0){
System.out.print(i + " ");
}
notAPrime=0; //In your program it is inside the if statement which makes it incorrect.
}
}
}
Output:
All prime numbers before number 50 are :
47 43 41 37 31 29 23 19 17 13 11 7 5 3
You can make your program more efficient by making the following changes:
public class primeNum {
public static void main(String[] args) {
int n=50;
int notAPrime=0;
System.out.println("All prime numbers before number " +n+ " are : ");
for(int i=n; i>2; i--){
if(i%2==0){
continue;
}
for(int j=3; j<i; j+=2){
if(i%j==0){
notAPrime++;
break;
}
}
if(notAPrime==0){
System.out.print(i + " ");
}
notAPrime=0;
}
}
}

Loops and Prime Numbers

Write a program that prompts the user for an integer and then prints out all prime numbers up to that integer. For example, when the user enters 20, the program should print
2 3 5 7 11 13 17 19
Recall that a number is a prime number if it is not divisible by any number except 1 and itself.
I am trying to write this program but I am having difficulties, can anyone show me how to write this code?
This is what I have written but it is completely wrong.
import java.util.Scanner;
public class PrimeNumbers
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter Integers: ");
int x;
int n = in.nextInt();
for (int i = 2; i < n ; i++)
{
x = i;
if (n % i != 0 && i % x != 0)
{
System.out.println(i);
}
x--;
}
}
}
Computes the number of primes less than or equal to N using
the Sieve of Eratosthenes.
% java PrimeSieve 25
The number of primes <= 25 is 9
% java PrimeSieve 100
The number of primes <= 100 is 25
% java -Xmx100m PrimeSieve 100000000
The number of primes <= 100000000 is 5761455
% java PrimeSieve -Xmx1100m 1000000000
The number of primes <= 1000000000 is 50847534
The 110MB and 1100MB is the amount of memory you want to allocate
to the program. If your computer has less, make this number smaller,
but it may prevent you from solving the problem for very large
values of N.
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 i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
}
}
}
// count primes
int primes = 0;
for (int i = 2; i <= N; i++) {
if (isPrime[i]){ primes++; System.out.print(i+", ");}
}
System.out.println("\nThe number of primes <= " + N + " is " + primes);
}
}
Use this method to check if a given int is a prime.
public static boolean isPrime(int a)
{
if ( a == 2)
return true;
int midpoint = Math.round(a/2);
for(int i = 2; i < midpoint; i++)
{
if(a % i == 0)
return false;
}
return true;
}
Explanation:
Loop through all the numbers until midpoint and modulus until you encounter 0 or not. If you encounter 0 then return false because we know that it is not prime, if we encounter no zero then we return true because it is prime.
We loop until midpoint because there is no need to loop further.
You can implement it in your loop via
for (int i = 2; i < n ; i++)
{
if (isPrime(i))
{
System.out.println(i);
}
}

Categories