I know this is not the best nor the most efficient way to find prime numbers; However, I can't seem to find the reason why 169 counts as a prime number (for smaller numbers it works OK as far as I'm concerned).
public static int checkPrime(int num, int i)
{
if (i == num)
return 1;
else
{
if (num % i == 0)
return 0;
else
checkPrime(num, i+1);
}
return 1;
}
Main Class:
System.out.println("Type a number");
number = reader.nextInt();
if ((number % 10) % 2 == 0)
result = 0;
else
result = checkPrime(number, 2);
if (result == 1 || number == 2)
System.out.println(number + " is a prime number");
else
System.out.println(number + " is NOT a prime number");
Replacing int by boolean for better expressiveness, and returning the value of the recursive call, your method looks like this:
public static boolean checkPrime(int num, int i)
{
if (i == num)
return true;
else
{
if (num % i == 0)
return false;
else
return checkPrime(num, i+1);
}
}
It still doesn't work for num < 2, it'll run until i overflows. So as your main prime checking function you can write something like:
public static boolean checkPrime(int num)
{
if(num<2)
return false;
else
return checkPrime(num, 2);
}
btw (number % 10) % 2 is equivalent to number % 2.
Related
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;
}
I am trying to solve a sample exercise which is to display Prime numbers based on the range inputted. For example if I inputted 10 it should output 2 3 5 7 11 13 17 19 23 29.
Here is my code:
System.out.print("Enter Range: ");
int range = input.nextInt();
int r = 0;
for(int ctr1 = 2; ctr1 <= range; ctr1++){
for(int ctr2 = 1; ctr2 <= ctr1; ctr2++){
if(ctr1%ctr2 == 0){
r++;
}
}
if(r == 2){
System.out.println(ctr1);
}
}
What happens is when I input 10 it just outputs 2. Can anyone please tell me the error in my codes?
Thanks...
Using nested loop in this case could make things more complicated. I would suggest you to divide the solution into two steps:
create a function to determine if a number is prime.
private static boolean isPrime(int n) {
//check if n is a multiple of 2
if (n % 2 == 0) return false;
//if not, then just check the odds
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0)
return false;
}
return true;
}
find the first N prime numbers with a loop:
System.out.print("Enter Range: ");
int range = input.nextInt();
int count = 0;
for (int number = 2; count < range; number++) {
if (isPrime(number)) {
count++;
System.out.println(number);
}
}
I didnt understand your code. Try to give reasonable parameter names. Anyway this the code that you are looking for.
public static void main(String args[]) {
//get input till which prime number to be printed
System.out.println("Enter the amount of prime numbers to be printed: ");
int limit = new Scanner(System.in).nextInt();
int count=1;
//printing primer numbers till the limit ( 1 to 100)
System.out.println("Printing prime number from 1 to " + limit);
for(int number = 2; count<=limit; number++){
//print prime numbers only
if(isPrime(number)){
System.out.println(number);
count++;
}
}
}
/*
* Prime number is not divisible by any number other than 1 and itself
* #return true if number is prime
*/
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false; //number is divisible so its not prime
}
}
return true; //number is prime now
}
One more solution)
public static boolean checkPrime(int i) {
if (i <= 1)
return false;
else if (i <= 3)
return true;
else if (i % 2 == 0 || i % 3 == 0)
return false;
int n = 5;
while (n * n <= i) {
if (i % n == 0 || i % (n + 2) == 0)
return false;
n = n + 6;
}
return true;
}
public static void main(String[] args) throws Exception {
int isPrime = 0;
int counter = 0;
int size = 10;
while (isPrime < size) {
counter++;
if (checkPrime(counter)) {
isPrime++;
System.out.println(counter);
}
}
}
the problem is below. main() checks numbers 1-10 by calling isPrime(). I think I have the math right however every number other than 2 comes back as not prime.
I have checked some of the solutions and questions on SO, however, I can't seem to achieve the same results.
original problem:
public class PrimeChecker {
// Returns 0 if value is not prime, 1 if value is prime
public static int isPrime(int testVal, int divVal) {
// Base case 1: 0 and 1 are not prime, testVal is not prime
// Base case 2: testVal only divisible by 1, testVal is prime
// Recursive Case
// Check if testVal can be evenly divided by divVal
// Hint: use the % operator
// If not, recursive call to isPrime with testVal and (divVal - 1)
return 0;
}
public static void main(String[] args) {
int primeCheckVal = 0; // Value checked for prime
// Check primes for values 1 to 10
for (primeCheckVal = 1; primeCheckVal <= 10; ++primeCheckVal) {
if (isPrime(primeCheckVal, (primeCheckVal - 1)) == 1) {
System.out.println(primeCheckVal + " is prime.");
}
else {
System.out.println(primeCheckVal + " is not prime.");
}
}
}
}
My solution so far:
public class PrimeChecker {
// Returns 0 if value is not prime, 1 if value is prime
public static int isPrime(int testVal, int divVal) {
int resultVal = 0;
if ((testVal == 0) || (testVal == 1)){
resultVal = 0;
}// Base case 1: 0 and 1 are not prime, testVal is not prime
else if (divVal == 1) {
resultVal = 1;
}// Base case 2: testVal only divisible by 1, testVal is prime
else {
if((testVal % divVal != 0) && (testVal / divVal == 1)) {
isPrime(testVal, (divVal-1));
}
else {
resultVal = 1;
}
}
return resultVal;
}
public static void main(String[] args) {
int primeCheckVal = 0; // Value checked for prime
// Check primes for values 1 to 10
for (primeCheckVal = 1; primeCheckVal <= 10; ++primeCheckVal) {
if (isPrime(primeCheckVal, (primeCheckVal - 1)) == 1) {
System.out.println(primeCheckVal + " is prime.");
}
else {
System.out.println(primeCheckVal + " is not prime.");
}
}
}
}
Change the if/else block
if((testVal % divVal != 0) && (testVal / divVal == 1)) {
isPrime(testVal, (divVal-1));
}
else {
resultVal = 1;
}
to
if (testVal % divVal != 0) {
return isPrime(testVal, (divVal-1));
} else {
resultVal = 0;
}
Basically, you've forgotten to return the result of your recursion, so the code carries on to return the wrong thing. If testVal % divVal == 0, the number is non-prime so you return zero. Also, don't use ints that only take the value of zero or one; use a boolean.
According your question, I think the following code would be easier.
public class PrimeChecker {
// Returns 0 if value is not prime, 1 if value is prime
public static int isPrime(int testVal, int divVal) {
// Base case 1: 0 and 1 are not prime, testVal is not prime
if (testVal <= 1) {
return 0;
}
// Base case 2: testVal only divisible by 1, testVal is prime
if (divVal == 1) {
return 1;
}
// Recursive Case
// Check if testVal can be evenly divided by divVal
// Hint: use the % operator
if (testVal % divVal == 0) {
return 0;
}
// If not, recursive call to isPrime with testVal and (divVal - 1)
return isPrime(testVal, divVal - 1);
}
public static void main(String[] args) {
int primeCheckVal; // Value checked for prime
// Check primes for values 1 to 10
for (primeCheckVal = 1; primeCheckVal <= 10; ++primeCheckVal) {
if (isPrime(primeCheckVal, (primeCheckVal - 1)) == 1) {
System.out.println(primeCheckVal + " is prime.");
}
else {
System.out.println(primeCheckVal + " is not prime.");
}
}
}
}
Please what could be the errors in my code and why is it printing the numbers rather than just prime numbers less than 10,000?
public class Isprime {
public static void main(String[] args) {
System.out.println("The prime numbers less that 10000 are:");
int number = 2;
printprime(number);
}
public static void printprime(int number) {
int pperline = 10;
int count = 0;
while (number < 10000) {
if (isprime(number)) {
count++;
}
if (count % pperline == 0) {
System.out.println();
} else {
System.out.print(number + ",");
}
number++;
}
}
public static boolean isprime(int number) {
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0)
return false;
}
return true;
}
}
You are calculating whether a number is prime or not just fine, but you aren't doing your print inside the condition that checks for that. This means your count of primes is correct, but you print something for every number, not just the prime ones.
You need to move your print statements inside your if (isprime(number)) check. Also, you are only print a prime or a newline. You should remove the else from your format logic so that you don't skip printing every 10th prime number:
public static void printprime(int number) {
int pperline = 10;
int count = 0;
while (number < 10000) {
if (isprime(number)) {
count++;
if (count % pperline == 0) {
System.out.println();
}
System.out.print(number + ",");
}
number++;
}
}
If you indent your code properly:
public static void printprime(int number) {
int pperline = 10;
int count = 0;
while(number < 10000){
if(isprime(number)){
count++;
}
if (count % pperline == 0) {
System.out.println();
}
else {
System.out.print(number+",");
}
number++;
}
}
You can see that it will print every number unless you've chosen to print a newline instead.
Move the ending brace for if(isPrime(number)) after the if/else. Also, you'll want to print the prime regardless of whether you need to print a newline, so move the print of the number outside of the else (and get rid of the else).
public static void printprime(int number) {
int pperline = 10;
int count = 0;
while(number < 10000) {
if(isprime(number)) {
count++;
if (count % pperline == 0) {
System.out.println();
}
System.out.print(number+",");
}
number++;
}
}
I think the error came from your first "if". Try to put something in the brackets {}
You may find my solution helpful so I'm posting it :)
public class Isprime {
public static void main(String[] args) {
System.out.println("The prime numbers less that 10000 are:\n");
int number = 2;
printprime(number);
}
public static void printprime(int number) {
int pperline = 10;
int count = 0;
while (number < 10000) {
if (isprime(number)) {
count++;
System.out.print(number + ", "); // consider printing out if and only if
// the number is actually a prime
// your solution is more complicated and you
// also miss some else if statement
if (count % pperline == pperline - 1) { // results from above approach, now we are printing endline after
// every 10 numbers
System.out.println();
}
}
number++;
}
}
public static boolean isprime(int number) {
// note that:
// 1) one is not a prime
// 2) you can easily prove that you don't have to check all the divisors up to number / 2
// you can optimize your code a bit by checking divisors up to the square root of number
for (int divisor = 2; divisor * divisor <= number; divisor++) {
if (number % divisor == 0)
return false;
}
return number >= 2; // checks if number was negative (negatives are not prime, 0 and 1 are also not prime)
}
}
So i have this problem where when i factor a number, lets say 15, i have to display this: 15=3x5 but instead what i get is 3x5x5 and i have no clue of how to make it that so it only displays 3x5. And then another problem i have is to find whether the number i inputted is a prime number or not. Any way of fixing this? I just need that and the other stuff im gonna edit after that.
public class PrimeFactor
{
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
int a;
int d;
int remainder=0;
int count=2;
int c=0;
String s;
System.out.println("Enter an integer to be factored:");
a=input.nextInt();
s="";
d=a;
while(a>1)
{
if(a>1)
{
s="";
while(a>1)
{
remainder=a%count;
if (!(remainder>0))
while(remainder==0)
{
remainder=a%count;
if (remainder==0)
{
a=a/count;
c=c+1;
s=s+count+"x";
if (a==1)
s=s+count;
}
else
count++;
}
else
count++;
}
if (a%count==0)
{
System.out.println(d +"=" + s);
System.out.println(d+" is a prime number.");
}
else
System.out.println(d +"=" + s);
}
// TODO code application logic here
}
}
}
This determines if the number is prime or not the quickest way. Another method would be to use a for loop to determine the number of factors for the number and then say it's prime if it has more than two factors.
int num; // is the number being tested for if it's prime.
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) // only have to test until the square root of the number
{
if (num%i == 0) // if the number is divisible by anything from 2 - the square root of the number
{
isPrime = false; // it is not prime
break; // break out of the loop because it's not prime and no more testing needed
}
}
if (isPrime)
{
System.out.println(num + " is a prime number.");
}
else
{
System.out.println(num + " is a composite number.");
}
You are not constructing the factorization string quite right:
When you find that 3 divides a=15 you set s to 3x and set a to the quotient, so a=5
When you find that 5 divides a=5 you append 5x to s, so now s is 3x5x. Then you set a to the quotient, which is 1. Since the quotient is now 1, you append 5 again, so now you get 3x5x5.
What you'll want to do is append only 5 when a=1, not 5x5. You have to change this:
s=s+count+"x";
if (a==1)
s=s+count;
to this:
if (a==1) {
s=s+count;
} else {
s=s+count+"x";
}
How about trying like this:-
for(int i = input-1; i > 0; i--) {
if((input % i) == 0) {
if(i == 1)
System.out.println("Number is a prime");
else
System.out.println("Number is not a prime");
break;
}
}
These are quite straight-forward methods you can use to factor a number and determine if it is a prime number:
public static int oneFactor(int i) {
for (int j = 2; j < i; j++) {
if (i % j == 0)
return j;
}
return -1;
}
public static Integer[] primeFactors(int i) {
List<Integer> factors = new ArrayList<Integer>();
boolean cont = true;
while (cont) {
int f = oneFactor(i);
if (i > 1 && f != -1) {
i /= f;
factors.add(f);
} else
factors.add(i);
if (f == -1)
cont = false;
}
return factors.toArray(new Integer[factors.size()]);
}
public static boolean isPrime(int i) {
if (i == 2 || i == 3)
return true;
if (i < 2 || i % 2 == 0)
return false;
for (int j = 3, end = (int) Math.sqrt(i); j <= end; j += 2) {
if (i % j == 0) {
return false;
}
}
return true;
}
I am sure one can use faster algorithms, but those would be at the cost of simplicity, and it doesn't seem like you need high speed methods.
They all operate on ints, but its easy to change them to work with longs.
If you have any questions, feel free to ask!
You want to write a loop which loops through numbers 1 to (Inputted Number). And if you found a factor, you print it and divide the input by the factor. (And test if it can be divided again by the same number), else then skip to the next number.
Keep doing this until your input divides down to 1.
This program will break the number down to prime factors:
public class Factor {
public static void main() {
//Declares Variables
int factor = 15;
int i = 2;
System.out.println("Listing Factors:\n");
while (factor>1) {
//Tests if 'i' is a factor of 'factor'
if (factor%i == 0) {
//Prints out and divides factor
System.out.println(i);
factor = factor/i;
} else {
//Skips to next Number
i++;
}
}
}
}
Output:
Listing Factors:
3
5