For loop generator that prints a composite number - java

I want my isPrimeNumber function to return a null (so it will not print any of the numbers in the isPrimeNumber function), but methods apparently cannot return null. I want the for loop to gloss over the numbers that print and the prime number function and print numbers that are not in the prime number function and one, i.e. the composite number. Here is what my code looks like:
//prints all composite numbers
public class App {
public static void main(String[] args)
{
for(int i = 1; i <= 10000; i++)
{
if (isPrimeNumber(i))
{
return null;
}else{
System.out.println(i);
}
}
}
public static boolean isPrimeNumber(int i) {
int factors = 0;
int j = 1;
while(j <= i)
{
if(i % j == 0)
{
factors++;
}
j++;
}
return (factors == 2);
}
}
The else statement in the main function is supposed to print all the numbers between 1 and 10000 that are composite. How would I fixed this ?

Don't return null when you find a prime number. Yyou can't return a value from a method with a void return type, but even if this code did pass compilation, you wouldn't want to leave the method when you detect a prime number.
Change the condition from
if (isPrimeNumber(i)) {
return null;
} else {
System.out.println(i);
}
to
if (!isPrimeNumber(i)) {
System.out.println(i);
}

Related

How do I get an if statement to check if a user given number is a prime number?

I am writing a very basic program in Java to check if a number given by the user is a prime number.
I have tried to use an if statement to check if the number divided by itself is equal to 1 as well as if it is divided by 1 it equals itself, but when I run the program and enter a number there is no reaction at all from the if statement.
package prime.java;
import java.util.Scanner;
public class Prime {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Welcome to Prime!\nPlease enter a number:");
Scanner Scan = new Scanner (System.in);
int number = Scan.nextInt();
System.out.println(number);
if (number%1 == number && number%number == 1) {
System.out.println(number + " is a prime num");
}
}
}
Am I using the right operators?
This can help you:
static bool isPrime(int number)
{
for (int i = 2; i < number; i++)
{
if((number% i) == 0)
{
// Not Prime
return false;
}
}
// Just Prime!
return true;
}
A prime number is not divisible by any numbers between 2 and (itself - 1).
This way, if you call 'isPrime()' inside the if, this just works.
Hope this can help you!
, but when I run the program and enter a number there is no reaction
at all from the if statement.
This is because the if condition is never fulfilled ( for example : n%n will be 0 always) .
Thus, you can keep a variable i that starts from 2 till number -1 and check if that number divided by i , the remainder should never be 0 .
public class PrimeNumber {
public static void main(String[] args) {
int k = 5;
boolean isPrime = true;
for (int i = 2; i < k; i++) {
if (k % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println("number " + k + " is prime");
} else {
System.out.println("number " + k + " is not prime");
}
}
}
and the output is :
number 5 is prime
You can write a isPrime function to check if a given number is a prime or not, like below
public static boolean isPrime(int n) {
// Corner case
if (n <= 1) {
return false;
}
// Check from 2 to n-1
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
And replace your
if (number%1 == number && number%number == 1)
to
if (isPrime(number)
This is more efficient:
boolean isPrime(int number) {
int root = (int) Math.sqrt(number);
for (int i = 2; i <= root; i++) {
if ((number % i) == 0) {
return false;
}
}
return true;
}
Looks like someone is doing a project Euler problem.
You are close but I would suggest maybe looking into how you check if something actually is a prime number as the other comment suggested.
Research also some specifics of prime numbers, I will give one away which is : no prime number ends with 5. Implementing such rules can drastically reduce your programs run time.
And also you want to check out the correct usage of the modulo (%) operator.
public static boolean isPrime(Long num){
String number = String.valueOf(num);
if(number.length() >= 2 ){
//Lets see if a number ends with 5 if it does it is divisible by 2 and not prime
if(number.endsWith("5")){
return false;
}
}
//No reason to check if a number is prime when it is 2.
else if (num == 2){
return true;
}
//Any number that can be devided by 2 with no remainder clearly isn't prime
else if(num % 2 == 0){
return false;
}
//All other numbers actually need to be checked.
else{
for (Long i = num -1; i > 2; i--) {
if(num % i == 0){
return false;
}
}
}
return true;
}

Get numbers that cannot be divided by anything

how can I use Java to find out numbers that can't be divided by any other number?
i have an int array:
int[] numbers = new int[25];
Now I want to iterate over this array and output all the numbers that are not divisible in a new array. The remaining numbers should no longer appear in the new array.
For example, in a range from 1-25, only the numbers [1,3,5,7,11,13,17,19,23] should be output as an array.
How exactly do I get to program this?
Thanks in advance!
Like #Selvin said in the comments, these numbers have a name, they are called "prime numbers".
For example, you can use something like this:
for (int number : numbers) {
if (!primeCal(number)) {
number = null;
}
}
private static void primeCal(int num) {
int count = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
count++;
}
}
if (count == 2) {
return true;
} else {
return false;
}
}
You must first iterate and then use the following method to check if any of them are prime numbers or not
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}

While loop in Java :: keep dividing while contion is not met

I have a basic code:
public class experiment {
public static void main(String[] args) {
System.out.println(experiment(80));
}
public static int experiment (int number) {
while (number > 10) {
number = number / 2;
return number;
} return -1;
}
}
It returns me 40.
So it means is not looping on the variable number.
I would like it to keep looping on number (80, 40, 20, 10), till it return 10.
Is there a way to do it without using the for loop?
Move the return out of the loop:
public static int experiment (int number) {
while (number > 10) {
number = number / 2;
}
return number;
}
If you need the -1 for a special case, you should check it before entering the loop:
public static int experiment (int number) {
if (number < 0) { // or some condition
return -1;
}
while (number > 10) {
number = number / 2;
}
return number;
}
BTW, start using a debugger, you can step through this kind of code and find the problem easily.
What wrong is that you put return number inside the while loop it will end the iteration and return the value of 40. So you have to,
public static int experiment (int number) {
while (number > 10) {
number = number / 2;
}
return number;
}
If you want all the numbers the loop has passed to print;
public static void experiment (int number) {
while (number > 10) {
number = number / 2;
System.out.println(number);
}
}
using recursion:
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(test.toTen(80));
}
public static int toTen(int k) {
if (k==10) {
return k;
}
else {
return toTen(k/2);
}
}
}
or simply edit the loop like so
while (k > 10) {
k = k / 2;
}
return k;

the output of 2nd for loop

i have this code here and I am having a really hard time to figure out that isn't when i == 6 that would result in two results in the second loop when 6%2 = 0 and 6%3 = 0 and 6%4 =2. so how the compiler decides which if 6 is a prime number or not
public static void main(String[] args) {
for (int i = 2; i < 100 ; i++) {
if (isPrime(i))
System.out.println(i);
}
}
private static boolean isPrime(int n) {
for (int i = 2; i < n; i++){
if (n % i == 0)
return false;
}
return true;
}
I am assuming that you are asking how the second loop knows 6 is prime or not.
In the second loop, if n is 6 then the loop will run once and then return false since 6%2==0. It will not check 6%3, 6%4 because the return statement was already called.
Basically, if the condition n%i== 0 is met, the return statement is called so no more values are checked. Remember that for prime numbers n%i == 0 can never be true anyways so there is no point in checking any other values.
This code prints every odd number as "prime" because the isPrime method will return false if (n%2 == 0) (first iteration), and true otherwise.
You could change your method to something like:
public static void main(String[] args) {
for (int i = 2; i <100 ; i++) {
if (isPrime (i))
System.out.println(i);
}
}
private static boolean isPrime(int n) {
for (int i =2; i< n; i++)
if (n%i == 0)
return false;
}
return true;
}

Finding prime numbers with a custom IsPrime method

I started learning Java about one month ago and today I saw this question I couldn't solve.
The question was:
Write a method named isPrime, which takes an integer as an argument and returns true
if the argument is a prime number, or false otherwise. Demonstrate the method in a complete program.
And the second part says:
Use the isPrime method that you wrote in previous program in a program that
stores a list of all the prime numbers from 1 through 100 in a file.
Here's my code, which doesn't work:
import java.io.*;
public class PrimeNumbers {
public static void main (String args[]) throws IOException {
PrintWriter outputFile = new PrintWriter("PrimeNumber.txt");
int j = 0;
for (int i = 0; i < 100; i++) {
isPrime(i);
outputFile.println("Prime nums are:" + i);
}
}
public static boolean isPrime (int j) {
int i;
for (j = 2; j < i; j++) {
if (i % j == 0) {
return false;
}
if (i == j) {
return true;
}
}
}
}
Your condition for returning true in isPrime - if (i == j) - can never be met, since it's inside a loop whose condition is j < i. Instead, just return true after the loop. If the loop ends without returning false, you know for sure that the input number is prime.
Your code that uses isPrime is not checking the value returned by this method. You must check it in order to decide whether to write the number to the output file.
import java.io.IOException;
import java.io.PrintWriter;
public class PrimeNumbers
{
public static void main(String args[]) throws IOException
{
PrintWriter primeNumbersWriter = new PrintWriter("PrimeNumber.txt");
for (int i = 0; i < 100; i++)
{
// You didn't do anything with the return value of isPrime()
if (isPrime(i))
{
primeNumbersWriter.println("Prime numbers are: " + i);
}
}
// Please close writers after using them
primeNumbersWriter.close();
}
public static boolean isPrime(int prime)
{
// Do not use the number to check for prime as loop variable, also it's
// sufficient to iterate till the square root of the number to check
for (int number = 2; number < Math.sqrt(prime); number++)
{
if (prime % number == 0)
{
return false;
}
}
// You didn't always return a value, it won't let you compile otherwise
return true;
}
}
Prime Number A prime number (or a prime) is a natural number greater
than 1 that has no positive divisors other than 1 and itself.
What should be the logic?
Pass a number to method.
Use loop to start a check of modulo % to find at least one number which can divide the passed number.
Check until we reached the value passedNumber.
If the modulo gives 0 for atleast one, it's not prime thank god!
If modulo is not 0 for any number ...oh man it's Prime.
What are the problems in your code?
You are looping correctly but using the variable j which is the limit and you are incrementing it!
If you want to loop through i < j how can the condition i == j be true?
If method is returning boolean why are you using method as void! Use that returned value.
You can just return false at the end if divisor not found!
We did it...Just try now!
about isPrime: First of all, u should loop for( j = 2; j*j <= i; j++)
the reason for this loop is that if a number isn't prime, its factor must be less or equal to the squared root of i, so there is no need to loop after that point
now, if loop didn't return false - return true`
about second function: use if before checking isPrime - if(isPrime(i)) {add i to list}
see here is your solution.
import java.util.Scanner;
public class Testing {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int number = Integer.MAX_VALUE;
System.out.println("Enter number to check if prime or not ");
while (number != 0) {
number = scnr.nextInt();
System.out.printf("Does %d is prime? %s %s %s %n", number,
isPrime(number), isPrimeOrNot(number), isPrimeNumber(number));
}
}
/*
* Java method to check if an integer number is prime or not.
* #return true if number is prime, else false
*/
public static boolean isPrime(int number) {
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 2; i < sqrt; i++) {
if (number % i == 0) {
// number is perfectly divisible - no prime
return false;
}
}
return true;
}
/*
* Second version of isPrimeNumber method, with improvement like not
* checking for division by even number, if its not divisible by 2.
*/
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
/*
* Third way to check if a number is prime or not.
*/
public static String isPrimeOrNot(int num) {
if (num < 0) {
return "not valid";
}
if (num == 0 || num == 1) {
return "not prime";
}
if (num == 2 || num == 3) {
return "prime number";
}
if ((num * num - 1) % 24 == 0) {
return "prime";
} else {
return "not prime";
}
}
}

Categories