Trouble with factor generator - java

I'm having some trouble in completing this factor generator from my programming class. It's supposed to take a number, and print out all the factors using the nextFactor method. When I set the number to factor to let's say 150, it prints out "1 2 3 5", where it's supposed to print "2 3 5 5". So, where should I go from here? I've looked at Java - Factor Generator program nextfactor method, but it didn't awnser any of my inqueries
public class FactorGenerator
{
//user inputs int from scanner in FactorTester class
public FactorGenerator(int i)
{
num = i;
}
//Checks to see if num can be factored, but does not factor it.
//Goes through all possible factors of num and returns true if the remainder == 0
public boolean hasMoreFactors()
{
for(int i = 1; i < num; i++)
{
//check if the remainder is anything other then 0
if(num % i == 0)
{
return true;
}
}
return false;
}
//Actually factors num and prints out the factor at the end of every loop.
public void nextFactor()
{
for(int i = 1; i < num; i++)
{
//check if the remainder is anything other then 0
if(num % i == 0)
{
System.out.println(i);
num /= i;
}
}
System.out.println("Done.");
}
private int num;
}

try this factors can duplicate so you need to loop until you have extracted all the instances of that factor
public void nextFactor()
{
for(int i = 2; i <= num; i++)
{
//check if the remainder is anything other then 0
while (num >= i && num % i == 0)
{
System.out.println(i);
num /= i;
}
}
System.out.println("Done.");
}
an alternative way is to do the increment in the body of the loop
public void nextFactor()
{
for(int i = 2; i <= num;)
{
//check if the remainder is anything other then 0
if (num % i == 0)
{
System.out.println(i);
num /= i;
} else {
i++;
}
}
System.out.println("Done.");
}

For starters, it will always print out 1 because any integer / 1 will always have remainder of zero. You can start i from 2 instead of 1 in your for if you want to skip 1.
I'd suggest something like this: (note this is based in part on BevynQ's answer below):
for(int i = 2; i <= num; i++){
while (num >= i && num % i == 0) {
System.out.println(i);
num /= i;
}
}

Related

Why is eclipse showing it is a dead code?

class PrimeNo {
public static void main(String[] args) {
int n = 8;// assumed to be any random number
int i;
if (n == 0 || n == 1)
System.out.println("Not a prime number");
else {
for (i = 3; i < n; i++) {
if (n % i == 0) {
System.out.println("Not a prime number");
} else {
System.out.println("Prime number");
}
break;
}
}
}
}
I have written a basic code to find a given number is Prime number or not? I tried this by not using flags. Let we assume "n" to be any number. When I run the code it prints both "Prime" and "Not Prime" in different lines. Also, why is this code a dead code? If we go through logic this code should have runned perfectly. Help me out guys!!!
Your break is the culprit, it will break at first iteration, i will never get incremented and hence dead code.
I have written a basic code to find a given number is Prime number or
not? I tried this by not using flags.
Given below is how you can do it without using a flag:
public class Main {
public static void main(String[] args) {
int n = 8;// assumed to be any random number
int i;
if (n == 0 || n == 1)
System.out.println("Not a prime number");
else {
for (i = 2; i < n; i++) {
if (n % i == 0) {
System.out.println("Not a prime number");
break;
}
}
// If n % i == 0 doesn't become true throughout the loop, it means n is prime
if (i == n) {
System.out.println("Prime number");
}
}
}
}
Output:
Not a prime number
Note that I have started the loop from 2 which is also a prime number.
Another important thing to consider is that you do not need to divide and check until n (i.e. i < n), checking till the square root of n is sufficient. Check this to learn more about it. Thus, an efficient way of doing it as follows:
public class Main {
public static void main(String[] args) {
int n = 8;// assumed to be any random number
int i, sqrt = (int) Math.sqrt(n);
if (n == 0 || n == 1)
System.out.println("Not a prime number");
else {
for (i = 2; i <= sqrt; i++) {
if (n % i == 0) {
System.out.println("Not a prime number");
break;
}
}
// If n % i == 0 doesn't become true throughout the loop, it means n is prime
if (i > sqrt) {
System.out.println("Prime number");
}
}
}
}
Output:
Not a prime number
Also, why is this code a dead code?
When your loop runs for i = 3, it will be terminated by break; statement. This, i++ will never get a chance to run and thus, it is a dead code.
Since you are using 'break;' in your code, for loop was running only once. This means the 'i++' part in your for loop was never been called and hence the dead code error.
You might want to write your logic something similar to this:
class PrimeNo {
public static void main(String[] args) {
int n = 8;// assumed to be any random number
int i;
boolean isNumberPrime = true;
if (n == 0 || n == 1)
isNumberPrime = false;
for (i = 2; i < n; i++) {
if (n % i == 0) {
isNumberPrime = false;
}
}
if (isNumberPrime) {
System.out.println("Number is prime number");
} else {
System.out.println("Number is not prime number");
}
}
}
Sorry I missed the no flag part. We could implement the code as below with no flags:
class PrimeNo {
public static void main(String[] args) {
int n = 8; // assumed to be any random number
int i;
if (n == 0 || n == 1)
System.out.println("Number is not prime number");
for (i = 2; n > 1 && i < n; i++) {
if (n % i == 0) {
System.out.println("Number is not prime number");
break;
} else if (i == n - 1) {
System.out.println("Number is prime number");
}
}
}
}

Determine the largest prime factor using a while loop and a for loop

I wanted to use a for and a while loop to obtain the prime factors of a number. My while loop example works fine which I have posted below my for loop example. However, my for loop does not work, and i am guessing that I can't use a continue in the same manner that I used it in the while loop. If this is true, then how would I accomplish this. I have not been able to find a basic beginners example of this using a for loop. Thanks
// My getting largest prime factor using a for loop
public class LargestPrime{
public static void main(String[] args) {
int number = 36;
int largestPrime = 0;
for ( int i = 2; i <= number; i++){
if (number % i == 0){
largestPrime = i;
number /= i;
continue;
}
System.out.println(" largest prime = " + i);
}
}
}
//*******************************************************************
//*******************************************************************
public class LargestPrime {
// gettting largest prime using a while loop
public static int getLargestPrime(int number) {
if (number <= 1) {
return -1;
}
int largestPrime = 0;
int count = 2;
while (count <= number) {
if (number % count == 0) {
largestPrime = count;
number = number / count;
continue;
}
count++;
}
return largestPrime;
}
}
The problem is that continue in a for loop executes the update part (i++), which your while loop didn't.
The other problem is that you're printing inside the loop.
There are multiple way to fix this:
Do i-- before continue, so it evens out to nothing with the i++. This is a fairly common way to handle this.
Since you don't have any code after the if statement, you don't need the continue.
for (int i = 2; i <= number; i++) {
if (number % i == 0) {
largestPrime = i;
number /= i;
i--; // to retry same `i` value
}
}
Do the i++ "yourself", i.e. not as part of for loop:
for (int i = 2; i <= number; ) {
if (number % i == 0) {
largestPrime = i;
number /= i;
continue;
}
i++;
}
Or:
for (int i = 2; i <= number; ) {
if (number % i == 0) {
largestPrime = i;
number /= i;
} else {
i++;
}
}
Use a while loop inside the for loop:
for (int i = 2; i <= number; i++) {
while (number % i == 0) {
largestPrime = i;
number /= i;
}
}
That can be shortened to:
for (int i = 2; i <= number; i++)
for (; number % i == 0; number /= i)
largestPrime = i;
Though rather than assign largestPrime repeatedly, you could do this:
for (int i = 2; i <= number; i++) {
if (number % i == 0) {
largestPrime = i;
do {
number /= i;
} while (number % i == 0);
}
}

Why is my program not continuing after the first 10 Palindromic numbers? And also Why is my isPrime method not returning false for the number 4?

I'm not sure why my ct is not going all the way to 100 even though I clearly set it to go until it reaches 100.
public class PalindromicPrime
{
public static void main(String [] args)
{
int ct = 0;
while(ct < 100)
{
if(isPalindrome(ct) && isPrime(ct))
{
if(ct % 10 != 0)
{
System.out.print(ct + " ");
}
else
{
System.out.print("\n");
}
}
ct++;
}
public static boolean isPalindrome(int p)
{
int palindrome = p;
int reverse = 0;
while (palindrome != 0)
{
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
if (p == reverse)
{
return true;
}
return false;
}
I'm assuming my isPrime code is wrong since I'm getting a 4 in my output. What's wrong with this method?
public static boolean isPrime(int p)
{
for(int i = 2; i < p/2; i++)
{
if(p % i == 0)
{
return false;
}
}
return true;
}
}
First change you should do in your method isPrime() is change this line
for(int i = 2; i < p/2; i++)
to
for(int i = 2; i <= p/2; i++) // you can easily find the reason why it is necessary(=)
And also you are printing palindromic numbers less than 100 which are prime,not first 100 palindrome numbers, if you want to print first 100 palindrome numbers you can take another counter which will keep track of the numbers printed.
You can modify your main method like this:
public static void main(String [] args)
{
int ct = 0,n=0; // n to count numbers printed/found
while(n < 100) // change the condition to check n<100
{
if(isPalindrome(ct) && isPrime(ct))
{
System.out.print(ct + " ");
if(n % 10 == 0)
{
System.out.println();
}
n++; // incementing n after a number is found!
}
ct++;
}
}
Your palindrome method is fine. It's your isPrime method that's not working because to check if a number is prime, you're supposed to test factors up to the square root of the number. So a simple change in the condition should do it,
public static boolean isPrime(int p)
{
for(int i = 2; i <= Math.sqrt(p); i++)
{
if(p % i == 0)
{
return false;
}
}
return true;
}
}
Change your isPrime function to following (replace < with <= as 4/2 is 2 and loop will not run at all for p=4):
public static boolean isPrime(int p) {
for (int i = 2; i <= p / 2; i++) {
if (p % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int ct = 2;
int count = -1;
while (count < 99) {
if (isPalindrome(ct) && isPrime(ct)) {
count++;
if (count % 10 == 0) {
System.out.print("\n" );
}
System.out.print(ct + " ");
}
ct++;
}
}
The only numbers that are palindrome and prime and less than 100 are:
1 2 3 5 7 11
Try changing the value of 100 to 102. Then you get the following output as 101 is the next palindromic prime after 11:
1 2 3 5 7 11 101

Checking if number is ugly

I'm doing this problem:
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Note that 1 is typically treated as an ugly number.
Here's my attempt:
public class Solution {
public boolean isUgly(int num) {
if (num == 1) {
return true;
}
for (int i = 7; i <= num / 2; i++) {
if (isPrimeFactor(i, num)) {
return false;
}
}
return true;
}
public boolean isPrimeFactor(int candidate, int num) {
return isPrime(candidate) && isFactor(candidate, num);
}
public boolean isPrime(int num) {
if (num == 2) {
return true;
}
if (num % 2 == 0) {
return false;
}
for (int i = 3; i <= Math.sqrt(num); i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
public boolean isFactor(int candidate, int num) {
return (num % candidate == 0);
}
}
Unfortunately, it fails on test input -2147483648. It returns true when it should be false.
Any idea what I've done wrong?
You simply forgot the following emphasized condition:
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Therefore, you just need to add a check for negative numbers inside your isUgly method:
if (num <= 0) {
return false;
}
As a side-note, you could perhaps improve a little the performance by swapping the conditions inside isPrimeFactor and testing isFactor(candidate, num) && isPrime(candidate) instead of isPrime(candidate) && isFactor(candidate, num). This is because it is faster to determine whether a number is a factor of another than determining if a number is a prime number.
I could propose a different but a lot faster solution O(logn) for this problem:
public static boolean isUgly(int num) {
if (num < 1) return false;
int temp;
do {
temp = num;
if (num % 2 == 0) num /= 2;
if (num % 3 == 0) num /= 3;
if (num % 5 == 0) num /= 5;
} while (temp != num);
return num == 1;
}
or an even faster approach in terms of modular checks (by splitting the do while loop):
public static boolean isUgly(int num) {
if (num < 1) return false;
int temp;
do {
temp = num;
if (num % 2 == 0) num /= 2;
} while (temp != num);
do {
temp = num;
if (num % 3 == 0) num /= 3;
} while (temp != num);
do {
temp = num;
if (num % 5 == 0) num /= 5;
} while (temp != num);
return num == 1;
}

beginner whats wrong with my method

public class assignment6part3 {
public static void main(String[] args) {
int q = 0;
for ( int count=1; count <= 10000; count++) {
if (Prime(count)) {
q = q + 1;
}
}
System.out.println("It comes out " + q + " times.");
}
public static boolean Prime(int n) {
if (n <= 1) {
return false;
}
for (int i = 1; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
I'm trying to get the number of prime numbers between 0 and 10000, but when I run this, it says there are 0 prime numbers. What part of the code is causing this error?
Inside your function Prime your for loop runs like ::
for(int i = 1; i < Math.sqrt(n); i++), starting from i = 1 and every number is divisible by 1 and hence 0 prime numbers.. :P
Initialization condition for i shall be i = 2
Other things you might consider changing ::
for (int i = 1; i < Math.sqrt(n); i++) shall be changed to
for (int i = 1; i <= Math.sqrt(n); i++)
NOTE :: A more optimal way to find Primes would be https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
The code is returning false before it actually checks the numbers, because every number is divisible by 1. Also, in some cases such as 25 and 49, the factors are not less than the square root. Try this:
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}

Categories

Resources