I tried this a lot, and debugged it a few times, everything seems to be working and largest prime does indeed become the largest prime even if it takes rather long.
I can't get the printed value from System.out.println. I could find it through the debugger but the value is too high to find fast just holding down step over.
It compiles as well so I am stumped about what's the issue here. I would be very happy to know what I did wrong.
Edit: The reason why I wrote this code in the first place is because in the site project euler it asked for the largest prime value that when divided with the value of primer gave a whole number.
Is there a way at least that would allow me to make it faster with the same value? this seems rather impractical.
package unit5;
public class Primefinder { public static void main(String[] args)
{
double primer = 600851475143d;
double largestprime = 0;
Boolean ifprime = false;
for(double x = 2d; x < primer; x++)
{
for(double z = 2d; z<x; z++)
{
if( (x%z == 0) && (z != x) )
{
ifprime = false;
break;
}
else {
ifprime = true;
}
}
if((ifprime != false) && (x > largestprime))
{
largestprime = x;
}
ifprime = false;
}
System.out.print(largestprime);
}
}
for other questions you might ask everywhere, please tell us that what is the purpose of your code. this way it is easier to get the fault.
the code you have written above runs completely but the numbers you have used are too big so you need to wait a lot, so that compiler be able to reach to this line:
System.out.print(largestprime);
use lower numbers (at least for test) or wait properly.
Your 'primer' Value is very big.
So, loop is taking very much time to reach at '600851475143' value.
Wait Sometime and it with show largest prime number
Related
I'm trying to write a Java program to calculate the square root of an integer x, without using in-built functions like Math.pow() . This is the approach I tried -
class Solution {
public int mySqrt(int x) {
if(x==0 || x==1)
return x;
// if(x>=2147395600)
// return 46340;
int i;
for(i=1 ; i*i<=x ; i++) {}
return i-1;
}
}
Without the commented part, I start getting errors if x is in the range 2147395600 <= x <= 2^31-1 (which is the upper limit of an int's value range in Java). For instance, for the input x=2147395600, the expected output is 46340 but the actual output is 289398. Why is this happening? Thanks to all in advance.
PS - I am aware there are other (better) methods to solve this problem, but I'd really like to know why this code behaves this way.
Since 46340 * 46340 = 2147395600, when i=46340, x=2147395600 and you reach the condition i*i<=x it evaluates to true since 2147395600 = 2147395600. So the loop counter will incremnet by 1 and in the next iteration we will get i=46341 and i * i will cause an overflow - 46341*46341 = -2147479015.
The loop condition will still be true, since -2147479015 <= 2147395600, and the loop will not stop.
You can replace the <= with =, and check for edge cases that may occur now.
I have a program that takes in 3 numbers (feet, inches, sixteenths) then multiplies them by x. Upon starting to write the output part, I ran into needing:
if (sixteenths4<16) {
sixteenths5=sixteenths4;
inches6=0;
}else if (16<=sixteenths4) {
sixteenths5=sixteenths4-16;
inches6=1;
}else if (32<=sixteenths4) {
sixteenths5=sixteenths4-32;
inches6=2;
}else if (48<=sixteenths4) {
sixteenths5=sixteenths4-48;
inches6=3;
} else {
sixteenths5=sixteenths4-64;
inches6=4;
}
I realize the last else is redundant as it will never happen. My issue is that since the total sixteenths could exceed 4-5 hundred, that would be a lot of if else blocks. Is there a better way to do this?
Remive all the if/else statements and use integer arithmetic instead.
This is equivalent code for all your code:
sixteenths5 = sixteenths4 % 16;
inches6 = sixteenths4 / 16;
I'm not quite sure what I'm having trouble with here and I'm hoping someone can help me. This is my first post on Stack Overflow, and I'm relatively new to programming, so I hope I don't offend anyone's sensibilities around here.
Here's the prompt (yes, it's a Project Euler question and please don't give the answer away): What is the lowest number which is divisible by every number between 1 and 20?
Here's what I coded:
int target = 21;
int divisor;
boolean success = false;
while (!success)
{
for (divisor = 1; divisor < 21; divisor++)
{
if (target % divisor != 0)
{
break;
}
else
{
if (divisor == 20)
{
success = true;
}
}
target++;
}
}
System.out.println(target);
The answer I'm getting (232792581) is being flagged as incorrect by P.E. Can anyone tell me what I'm getting wrong here?
Thanks everyone!!
Your problem is that you have target++ in the wrong place. The way your code is now, this is being called inside the for loop where you test the numbers - i.e. you change the target while checking things against it. Move the target++ statement so that it is out of the for loop but still in the while loop.
I can't seem to figure this one out. I need to count how many numbers below a given number in which it is divisible.
Here is what I've tried:
public int testing(int x) {
if (x == 0) {
System.out.println("zero");
return x;
}
else if ((x % (x-1)) == 0) {
System.out.println("does this work?");
x--;
}
return testing(x-1);
}
That doesn't work and I don't know where to go from here. Anyone know what to do?
This is what is wrong:
public int testing(int x) {
If you want to make it recursive, you need to pass both the number to test and the number that you are currently checking. The first one will not change through the recursion, the second one will decrement. You cannot do what you express with only one parameter (unless you use a global variable).
This is not a task that should be solved with recursion.
If you MUST use recursion, the simplest way to do it is to have a second parameter, which is essentially an "I have checked until this number". Then you can increase/decrease this (depending on if you start at 0 or the initial number) and call the recursive on that.
Thing is, Java isn't a functional language, so doing all this is actually kind of dumb, so whoever gave you this exercise probably needs a bop on the head.
Your problem is that your expression x % (x - 1) is using the "current" value of x, which decrements on every call to the recursive function. Your condition will be false all the way down to 2 % (2 - 1).
Using a for loop is a much better way to handle this task (and look at the Sieve of Eratosthenes), but if you really have to use recursion (for homework), you'll need to pass in the original value being factored as well as the current value being tried.
You have a problem with your algorithm. Notice the recursion only ends when x == 0, meaning that your function will always return 0 (if it returns at all).
In addition, your algorithm doesn't seem to make any sense. You are basically trying to find all factors of a number, but there's only one parameter, x.
Try to make meaningful names for your variables and the logic will be easier to read/follow.
public int countFactors(int number, int factorToTest, int numFactors)
{
if (factorToTest == 0) // now you are done
return numFactors;
else
// check if factorToTest is a factor of number
// adjust the values appropriately and recurse
}
There is no need to use recursion here. Here's a non-recursive solution:
public int testing(int n) {
int count = 0;
for (int i = 1; i < n; i++)
if (n % i == 0)
count++;
return count;
}
BTW, you should probably call this something other than testing.
Using recursion:
private static int getFactorCount(int num) {
return getFactorCount(num, num - 1);
}
private static int getFactorCount(int num, int factor) {
return factor == 0 ? 0 : (num % factor == 0 ? 1 : 0)
+ getFactorCount(num, factor - 1);
}
public static void main(String[] args) {
System.out.println(getFactorCount(20)); // gives 5
System.out.println(getFactorCount(30)); // gives 7
}
I am a newbie Computer Science high school student and I have trouble with a small snippet of code. Basically, my code should perform a basic CLI search in an array of integers. However, what happens is I get what appears to be an infinite loop (BlueJ, the compiler I'm using, gets stuck and I have to reset the machine). I have set break points but I still don't quite get the problem...(I don't even understand most of the things that it tells me)
Here's the offending code (assume that "ArrayUtil" works, because it does):
import java.util.Scanner;
public class intSearch
{
public static void main(String[] args)
{
search();
}
public static void search()
{
int[] randomArray = ArrayUtil.randomIntArray(20, 100);
Scanner searchInput = new Scanner(System.in);
int searchInt = searchInput.nextInt();
if (findNumber(randomArray, searchInt) == -1)
{
System.out.println("Error");
}else System.out.println("Searched Number: " + findNumber(randomArray, searchInt));
}
private static int findNumber(int[] searchedArray, int searchTerm)
{
for (int i = 0; searchedArray[i] == searchTerm && i < searchedArray.length; i++)
{
return i;
}
return -1;
}
}
This has been bugging me for some time now...please help me identify the problem!
I don't know about the infinite loop but the following code is not going to work as you intended. The i++ can never be reached so i will always have the value 0.
for (int i = 0; searchedArray[i] == searchTerm && i < searchedArray.length; i++)
{
return i;
}
return -1;
You probably mean this:
for (int i = 0; i < searchedArray.length; i++)
{
if (searchedArray[i] == searchTerm)
{
return i;
}
}
return -1;
I don't know what is the class ArrayUtil (I can not import is using my Netbeans). When I try to change that line with the line int[] randomArray = {1 , 2, 3, 5, 7, 10, 1 , 5}; It works perfectly.
And you should change the loop condition. I will not tell you why but try with my array and you will see the bug soon. After you see it, you can fix it:)
There are 4 basic issues here.
1. Putting searchedArray[i] == searchTerm before i < searchedArray.length can result in an out-of-bounds exception. You must always prevent that kind of code.
2. Your intention seems to be the opposite of your code. Your method name implies finding a search term. But, your code implies that you want to continue your loop scan until the search term is not found, although your loop won't do that either. Think of "for (; this ;) { that } " as "while this do that".
3. Place a break point at the beginning of "search". Then, with a small array, step through the code line by line with the debugger and watch the variables. They don't lie. They will tell you exactly what's happening.
4. Please use a standard IDE and compiler, such as Eclipse and Sun's JDK 6 or 7. Eclipse with JDK 7 is a serious combination that doesn't exhibit a strange "infinite loop" as you describe above.