Original: So for my intro to programming class, we have to find the prime factors of a range of numbers that the user inputs (i.e. 59-65). The issue with a lot of the solutions here is that they use things that we haven't discussed in class like arrays, continue, etc. It's a pretty basic class. As for the requirements, we have to use a primeFact method/function that we call in the first for loop. She instructed us to use a while and for loop in the method to get the prime factors but everytime I think I have something, it doesn't come out right. Any help is really appreciated and my code is below. I really only need help with the method portion with the algorithm for finding the factors.
Edit: Here is the final solution that I turned in. It works and will give all prime factors of all numbers in a given range of numbers.
import java.util.Scanner;
public class PrimeFact {
public static void main(String[] args) {
int start, stop;
//Get input
Scanner input = new Scanner(System.in);
System.out.println("Please enter then two values with the lower value first");
start = input.nextInt();
stop = input.nextInt();
input.close();
//Displays for the start of the loop
System.out.println("Starting value (at least two digits): "+start);
System.out.println("Ending value (at least two digits): "+stop);
System.out.println("Prime factors for numbers between "+start+" and "+stop);
//Loop for the prime factors
for (int num = start; num <= stop; num++) {
primeFact(num);
}
}
// Method for Prime Factoring
public static void primeFact(int num) {
int divisor = 2;
System.out.print(num+" = ");
while (num>1) {
if ((num%divisor) == 0) {
System.out.print(divisor+" x ");
num=num/divisor;
} else {
divisor++;
}
}
System.out.print("1");
System.out.println();
}
}
public static void primeFact(int num) {
System.out.print(num+" = ");
for(int i=2;i<num;i++)
{
if(num%i==0)
{
if(isPrime(i))
{
System.out.println("Prime Factor for "+num+" is:"+i);
}
}
}
if(num==2)
System.out.println("Prime Factor for "+num+" is:"+num);
}
static boolean isPrime(int num){
for(int i=2;i<num;i++)
{
if(num%i==0)
{
return false;
}
}
return true;
}
//if u want use while replace the for loop like
public static void primeFact(int num) {
System.out.print(num+" = ");
int i=2;
while(i<num)
{
if(num%i==0)
{
if(isPrime(i))
{
System.out.println("Prime Factor for "+num+" is:"+i);
}
}
i=i+1;
}
if(num==2)
System.out.println("Prime Factor for "+num+" is:"+num);
}
static boolean isPrime(int num){
int i=2;
while(i<num)
{
if(num%i==0)
{
return false;
}
i=i+1;
}
return true;
}
you're method is pretty close to a solution. but your while loop is invalid.
remember it should be like this:
while(<boolean statement>){
//code here
}
I will reference the variable we are checking "primality" for as "num"
here's how to check for factors with a while loop:
//remember, num is given to us in the parameters of primeFact(int num).
boolean isPrime = true; //we are optimistic.
//we start at 2 because everything is divisible by one
int posFact = 2; //short for "possible factor"
while(posFact < num){ //this will start at 2, and go to 1 less than num
if(num % posFact == 0){ // "%" gives us remainder
isPrime = false; // we now know it's not prime
System.out.println("The number " + posFact + " is a factor of " + num + ".");
}
posFact++; //increments posFact up by 1
}
if(isPrime){ //This will only be true if the number is prime
System.out.println("The number " + num + " is prime!");
}
We can do the exact same thing with a for loop:
//remember, num is given to us in the parameters.
boolean isPrime = true; //we are optimistic.
for(int posFact = 2; posFact < num; posFact++){ //posFact's initialization and incrementation was moved here.
if(num % posFact == 0){ // "%" gives us remainder
isPrime = false; // we now know it's not prime
System.out.println("The number " + posFact + " is a factor of " + num + ".");
}
}
if(isPrime){ //This will only be true if the number is prime
System.out.println("The number " + num + " is prime!");
}
Related
I'm having trouble implementing 3 methods to create a program that checks if a number is prime. When I call my methods and run the program the only value that shows is 0. I'm assuming this has to do with variables or logic in my methods
I have tried using different variables to store user input then using that variable as an argument in my methods.
package practice;
import java.util.Scanner;
public class Practice {
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
//int result = 0 ; //stores number user picks
int numPicked = 0; //
int endResults = 0; //stores result of calculation
// Calling methods
isPrime(numPicked);
pickedNum(numPicked);
results(endResults);
}
// Method to check if numbers are prime
public static boolean isPrime(int numPicked){
if (numPicked <= 1) {
return false;
}
for (int i = 2; i <= numPicked; i++) {
if (numPicked % i == 0) {
return false;
}
}
return true;
}
// Method that asks user for a positive integer
public static int pickedNum (int userNumbers){
Scanner s = new Scanner(System.in);
System.out.println("Type a positive number that you want to know if it's prime or not.");
int numPicked = s.nextInt();
return numPicked;
}
// Method that displays result of calculation
public static int results (int numPicked){
if(numPicked == 0 && numPicked != 1 ){
System.out.println( numPicked + " is a Prime Number");
}
else{
System.out.println(numPicked + " is Not a Prime Number");
}
return numPicked;
}
}
I need to fix the logic within my methods to be able to call them correctly.
I did some correction in your code and working version is below. There is a lot of things that should be also changed but I tried to make your program working without big changes.
So first of all, You had 2 Scanners so I deleted one of them. Second thing your isPrime method was not working correctly so I replace it with working version. Other thing was that you called isPrime before loading value which was main problem that you always got 0. Other thing is that java is pass by value it means that if you put int as argument and you modify it inside method you still have old value so you have to assign returned value to your value again
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
//int result = 0 ; //stores number user picks
int numPicked = 0; //
boolean isPrime = false;
// Calling methods
numPicked = pickedNum();
isPrime = isPrime(numPicked);
results(numPicked, isPrime);
}
// Method to check if numbers are prime
public static boolean isPrime(int numPicked) {
if (numPicked == 2)
return true;
if (numPicked < 2 || numPicked % 2 == 0)
return false;
for (int i = 3; i * i <= numPicked; i += 2)
if (numPicked % i == 0)
return false;
return true;
}
// Method that asks user for a positive integer
public static int pickedNum()
{
System.out.println("Type a positive number that you want to know if it's prime or not.");
int numPicked = s.nextInt();
return numPicked;
}
// Method that displays result of calculation
public static int results (int numPicked, boolean isPrime)
{
if(isPrime)
{
System.out.println( numPicked + " is a Prime Number");
}
else
{
System.out.println(numPicked + " is Not a Prime Number");
}
return numPicked;
}
package test;
import java.util.Scanner;
public class Practice {
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
int numPicked = 0; //
Commented out endResults as it currently has no functionality.
//int endResults = 0; //stores result of calculation
Added a Boolean to record whether isPrime is true or false
boolean isPrime;
numPicked now stores the returned value of the pickedNum method and it takes no parameters.
// Calling methods
numPicked = pickedNum();
isPrime = isPrime(numPicked);
Pass the Boolean value to the results method, true or false.
results(numPicked, isPrime);
}
// Method to check if numbers are prime
public static boolean isPrime(int numPicked)
{
if (numPicked <= 1) {
return false;
}
Removed <= with just less than. This is as if numPicked equals its own value it will return false. In reality a prime number can only be divided by itself so you just need to check the numbers less than it.
for (int i = 2; i < numPicked; i++) {
if (numPicked % i == 0) {
return false;
}
}
return true;
}
// Method that asks user for a positive integer
public static int pickedNum ()
{
Scanner s = new Scanner(System.in);
System.out.println("Type a positive number that you want to know if it's prime or not.");
int numPicked = s.nextInt();
return numPicked;
}
// Method that displays result of calculation
public static int results (int numPicked, boolean isPrime)
{
Checks if isPrime is true.
if(isPrime)
{
System.out.println( numPicked + " is a Prime Number");
}
else
{
System.out.println(numPicked + " is Not a Prime Number");
}
return numPicked;
}
}
I'm trying to write a program that asks the user to enter a number, then I need to create a method called isPrime to create the calculation and print out the result in main. I'm sure it's something small that I'm missing, but I can't get it to produce an accurate result.
public static void main(String[] args) {
System.out.print("Enter number: ");
int num = s.nextInt();
if (isPrime(num) == true) {
System.out.println("Number is prime");
} else if (isPrime(num) == false) {
System.out.println("Number is not prime");
}
}
public static boolean isPrime(int num){
for(int i = 2; i <= num/2; i++) {
if (num%i != 0) {
return true;
}
}
return false;
}
Use an if and else (don't retest your boolean condition in the first case). And don't test for == true in an if. This
if(isPrime(num) == true)
{
System.out.println("Number is prime");
}
else if(isPrime(num) == false)
{
System.out.println("Number is not prime");
}
Should just be
if (isPrime(num)) {
System.out.println("Number is prime");
} else {
System.out.pritnln("Number is not prime");
}
or even something like
System.out.print("Number is ");
if (!isPrime(num)) {
System.out.print("not ");
}
System.out.println("prime");
If you want to put the braces on their own lines go ahead. As for your isPrime method; you have your return conditions reversed (and the test as well). Also we can optimize it a bit. Unroll the first even test, because then we can skip every other element. Also we only need to test to the square root of the input number. Like,
public static boolean isPrime(int num) {
if (num == 2) {
return true; // two is prime.
}
if (num < 1 || num % 2 == 0) {
return false; // all other even numbers are not prime.
}
for(int i = 3; i <= Math.sqrt(num); i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
The isPrime(int num) method may need to check if num % i == 0 instead of if num % i != 0 because many non-prime numbers will pass the condition and return true.
As an example, if isPrime(9) is called, the conditional will check if 9 % 2 != 0, which is true, and the method will say that 9 is prime when it's not.
As a result, you could try changing the method to something like this:
public static boolean isPrime(int num)
{
for(int i = 2; i <= num/2; i++)
{
if (num%i==0)
{
return false;
}
}
return true;
}
You should change your "if (num%i!=0)" condition to if(num % i == 0)
See the following code:
public class Prime {
public static void main(String[] args) {
int num = 29;
boolean flag = false;
for(int i = 2; i <= num/2; ++i)
{
// condition for nonprime number
if(num % i == 0)
{
flag = true;
break;
}
}
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
import java.util.Scanner;
public class exam2015q2
{
public static void main (String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Eneter a number");
int num = scan.nextInt();
int num1 = num-1;
int count = 0;
if(num % 2 == 0)
{
count++;
System.out.println(+num+ " Is an even number");
}
else
{
System.out.println(num+" Is an odd number");
}
boolean isPrime = true;
do {
if(num % num1 == 0)
{
isPrime = false;
break;
}
num1--;
}
while(num1 >= 2);
if(isPrime == true)
{
System.out.println(num +" is a prime number as it is only divisible by 1 and " +num);
}
else
{
System.out.println(num +" is NOT a prime number.It is divisible by " +count);
}
}
}
in this i need to output if its not a prime number then we have to output what number it is divisible by but i cant get that to print it out. i need help on this can someone give me suggestions on how to get the number for divisible by
public static void main (String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Eneter a number");
int divisibleBy;
int num = scan.nextInt();
int num1 = num-1;
int count=0;
if(num%2==0)
{
count++;
System.out.println(+num+ " Is an even number");
}
else
{
System.out.println(num+" Is an odd number");
}
boolean isPrime = true;
do{
if(num%num1==0)
{
divisibleBy = num1;
isPrime = false;
break;
}
num1--;
}
while(num1>=2);
if(isPrime == true)
{
System.out.println(num +" is a prime number as it is only divisible by 1 and " +num);
}
else
{
System.out.println(num +" is NOT a prime number.It is divisible by " +divisibleBy);
}
}
Just change your statement showing the variable the number is divisible by from count to num1, since you determine in your do loop that num can be divided by num1 already.
else{
System.out.println(num +" is NOT a prime number.It is divisible by " +num1);
}
You can get rid of count entirely in your program as it is shown.
I wrote the following program which displays if a number is a prime and if not a prime it display its prime factors and the next prime number.
However, I am not sure how to have the program ask the user if he/she wishes to input another number.
The user must answer either yes, no, y or n using any combination of lower and upper case letters.
If an invalid answer is given, the program must be informed that the answer was not acceptable, and then be prompted again for another answer. The program will only prompt up to three tries otherwise the program will exit.
If the answer is Yes (in any allowed form), the program must continue from step in the main function.
The program is written in prototype methods because that is what is called for.
If anyone can assist a newbie with the last part, i would greatly appreciate it.
code:
package primefactors;
import java.util.Scanner;
public class Primefactors {
//------------------three tries check method-------------------
public static int getNumberWithThreeTries(int m) {
int count = 1;
int number;
String s = "tries";
while (count <= 3) {
number = getInputNumber(m); //getScore returns -1 for invalid inputs
if (number <= 1) {
if ((3 - count) < 2) {
s = "try"; //just make sure that singular /plural form in the next statme is correct
}
if (count == 3) {
System.out.println("No more tries remaining!\n");
} else {
System.out.println((3 - count) + " " + s + " remaining! Try Again! \n");
}
count = count + 1;
} else {
return number;
}
}
return -1;
}
//-------------------boolean try again---work in progress---------------
public boolean askRunAgain() {
System.out.println("Would u like to solve more problems? ");
Scanner scanner = new Scanner(System.in);
boolean askRunAgain = scanner.nextBoolean();
return askRunAgain;
}
//----------------------------------boolen prime check method------------------
public static boolean isPrime(int m) {
for (int i = 2; i * i <= m; i++) {
if (m % i == 0) {
return false;
}
}
return true;
}
//------------------------next prime method-----------------
private static int nextPrime(int m) {
if (m % 2 == 0) {
m = m + 1;
}
for (m = m; !isPrime(m); m = m + 2)
;
return m;
}
//---------------------primefactors----------------------
public static String getPrimeFactors(int m) {
String ans = "";
for (int i = 2; i <= m; i = i + 1) {
if (m % i == 0) {
ans += i + "*";
m = (m / i);
i--;
}
}
return (ans.substring(0, ans.length() - 1));
}
//----------------------------------------------------------
public static int getInputNumber(int m) {
Scanner n = new Scanner(System.in);
int number = 0;
System.out.println("Enter an Integer greater than 1");
if (!n.hasNextInt()) {
System.out.print("That's not a number! you have ");
n.next();
return -1;
}
number = n.nextInt();
if (number <= 1) {
return -1;
}
return number;
}
//------------------------------main method ----------------------
public static void main(String[] args) {
int number;
int count = 0;
number = getNumberWithThreeTries(1);
if (number <= 1) {
System.out.println("Program Terminated");
System.exit(0);
}
if (isPrime(number)) {
System.out.println(number + ": Is a Prime Number \n\n"
+ getPrimeFactors(number) + ": Is its prime factor");
} else {
System.out.println(number + " Is not a Prime number\n\n"
+ getPrimeFactors(number) + " Are its prime factors \n\n"
+ nextPrime(number) + " Is the next Prime number\n ");
}
}
}
You need to place the getNumberWithThreeTries within a while loop, which at the end, ask if the user wants to try again. If they say yes, then your while loop should then continue to execute again, otherwise, it should exit.
We have as an exercise the task of finding errors in the following loop. The task of the loop is to output the number of digits of a number before the ".", i.e. "32782.12" would be equal to 5. Now so far, I really do not see any error. The only thing that is the case is that an input = 0 would not lead to a correct answer - do you have me any hint?
public class countingDigits {
public static void main(String[] args) {
double number = 88888888.99;
for(int digits=0; digits<6; ++digits) {
if (number*number < 1) {
System.out.println("The number has " + digits + " digits");
break;
}
number /= 10;
}
}
}
Is is not unusual to handle the special cases separately:
0
-0 (where applicable...)
maximum value of datatype (Double.MAX_VALUE)
minimum value of datatype (Double.MIN_VALUE)
etc.
So I'd handle 0 this way:
if(number==0.0 ) {
return 1;
}
public void countingDigits {
public static void main(String[] args){
double number = 88888888.99;
if (number == 0){
System.out.println("The number has 1 digits");
}else {
for(int digits=0; digits<20; ++digits) {
if (number < 1) {
System.out.println("The number has " + digits + " digits");
break;
}
number /= 10;
}
}
}