This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm working on application which should show the biggest factor of a number and it has to be the prime number too.
That's my app:
public class BiggestFactor {
public static void main(String[] args) {
double dev = 0d;
for (double j = 0; j < 984654354654d; j++) {
if (984654354654d % j == 0) {
dev = j;
}
// show dev when is a prime number
double i;
for (i = 2; i < dev; i++) {
double n;
n = dev % i;
if (n == 0) {
// do nothing - not a prime number
break;
}
}
if (i == dev) {
System.out.println(dev);
}
}
}
}
and my question is how to get as a result just the last number? In my case I get bunch of numbers.
The minimal change is to declare a new variable result:
double result = -1;
and instead of printing dev, simply save its value in result:
if (i == dev) {
result = dev;
}
Then, at the end of the function, print result:
System.out.println(result):
public class BiggestFactor
{
public static void main(String[] args)
{
double dev = 0d;
double last = dev;
for (double j = 0; j < 984654354654d; j++)
{
if (984654354654d % j == 0)
{
dev = j;
}
double i;
for (i = 2; i < dev; i++)
{
double n;
n = dev % i;
if (n == 0)
{
break;
}
}
if (i == dev)
{
last = dev;
}
}
System.out.println(last);
}
}
I have done a little refactoring and moved the logic of checking prime in another function for better understanding. Also change the number to 1001 to increase the verification speed :P
public class BiggestPrimeFactor {
public static void main(String[] args) {
double dev = 0d;
double numberToCheck = 1001d;
for (double j = 0; j <= numberToCheck / 2; j++) {
if (numberToCheck % j == 0 && isPrime(j)) {
dev = j;
}
}
System.out.println(dev);
}
private static boolean isPrime(double n) {
boolean prime = true;
for (long i = 2; i <= n / 2; i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
return prime;
}
}
Basically, what is does it to continuously update dev to be the current biggest prime factor.
Related
I wrote a program that didn't work for project Euler problem 50, so if you haven't solved that one probably don't look if you want too solve it.
the problem is linked here:https://projecteuler.net/problem=50
Spoiler to answer below
My answer was 997661, which was exactly ten more than the real solution
My program seems to function to me, but I am inexperienced and was hoping that a more experienced programmer could find what was wrong.
import java.util.ArrayList;
public class ConsecutivePrimeSum {
public static void main(String[] args) {
ArrayList<Integer> primes = new ArrayList<Integer>();
for (int i = 2; i < 1000000; i++) {
if (isPrime(i)) {
primes.add(i);
}
}
int total = 0;
int counter = 0;
while (total + primes.get(counter) < 1000000) {
total += primes.get(counter);
System.out.println(primes.get(counter));
counter += 1;
}
System.out.println(total + " " + counter);
}
public static boolean isPrime(Integer number) {
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 2; i < sqrt; i++) {
if (number % i == 0 && number != i) {
return false;
}
}
return true;
}
}
I want my program to get all the even digits from a number input. Then multiply those with digits with 2. If the result is a two digit number, add them. At the end i want it to give me the sum of all the even digits.
public class evenplaceadd {
public static void main(String[] args) {
System.out.println(sumOfevenPlace(5566));
}
public static int sumOfevenPlace(int number)
{
int maxDigitLength = 4;
int sum = 0;
for (int i = 0; i < maxDigitLength; i++)
{
if (i % 2 == 0)
{
int digita = number % 10;
int digitb =digita*2;
int digitc;
if(digita < 9)
{
sum = sum + digitb;
}
else if(digitb>9)
{
digitc =(digitb % 10)+ (digitb /10);
sum =sum + digitc;
}
}
else
{
number = number/10;
}
}
return sum;
}
}
Your code seems ok for the most part. There are some minor flaws in the code which I am sure you will be able to figure out after understanding the code provided below. I have changed it up a bit and made it easier to read. Please confirm it is working, and next time please provide the code when asking question. I know you are new to the community, and so am I. Its a learning experience for all of us. All the best in the future :)
public static void int sumOfEvenDigits(int num){
int sum = 0;
int lastDig = 0;
while(num/10 != 0)
{
lastDig = num % 10;
num = num / 10;
if(lastDig % 2 != 0)
{
continue;
}
if(lastDig > 10)
{
sum += lastDig / 10;
sum += lastDig % 10;
}
else
{
sum += lastDig;
}
}
return sum;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This code is meant to find the 1001st prime but gives me the answer 47 which is clearly wrong.
public class problem7 {
public static void main(String[] args) {
int[] myarray = new int[1001];
int j = 0;
boolean prime = false;
for (int i = 2;; i++) {
for (int k = 2; k < i; k++) {
if (i == (k - 1) && i % k != 0) {
prime = true;
}
if (i % k == 0) {
prime = false;
prime = true;
}
if (prime) {
myarray[j] = i;
}
if (j == 1000) {
System.out.println(myarray[1000]);
return;
}
j++;
}
}
}
}
Any help would be greatly appreciated.
Your check for prime is wrong: you cannot declare a number prime and set prime = true based on a single test. The inner loop should set prime to false, but it shouldn't reset it to true: once it's false, it's false.
The algorithm should proceed as follows:
For each i, set prime=true
Loop over potential divisors k
If a divisor such that i % k == 0 is found, set prime = false, and break the loop
If prime is still true at the end of the nested loop, add i to the list of primes.
This should give you a correct result, at which point you should consider optimizing your solution using considerations below:
If you did not find a divisor among k below or at sqrt(i), then i is prime
You do not have to try all numbers k, only the ones from the list of primes that you have discovered so far.
I think j++ is increment only if prime number is inserted not at all case.By using this code you will be get your 1001 Prime number
public static void main(String[] args) {
int[] myarray = new int[1001];
int j = 0;
for (int i = 2;; i++) {
boolean prime = false;
for (int k = 2; k < i; k++) {
if (i % k == 0) {
prime = true;
}
}
if (!prime) {
myarray[j] = i;
j++;
}
if (j == 1001) {
break;
}
}
for (int primeNumber : myarray) {
System.out.println(primeNumber);
}
}
This is an implementation of dasblinkenlights algorithm!
public static void main(String args[]) {
int[] primes = new int[1001];
int i = 1;
int index = 0;
while (primes[1000] == 0) {
i++;
boolean skip = false;
for (int i1 : primes) {
if (i1 == 0)
break;
if (i % i1 == 0) { //checks if the number is a multiple of previous primes, if it is then it skips it
skip = true;
break;
}
}
if (!skip) {
if (isPrime(i)) {
primes[index] = i;
System.out.println(i);
index++;
}
}
}
}
static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return true;
}
The primality test you done here is kind of ambiguous. Because the general approach is, we pick any number assuming its prime, so at the beginning, prime = true. Then if there exist any factor k of input such that k < input and kthen the number is not prime, so prime = false.
I modified your code and get a result: 104743 .
Update: Here is a bit faster way to find large prime. The inner loop will iterate up to square root of i, reason: Why do we check upto the square root of a prime number to determine if it is prime?
public static void main(String[] args) {
int[] myarray = new int[10001];
int j = 0;
boolean prime = true;
int i = 2;
while (true) {
prime = true;
for (int k = 2; k*k <= i; k ++) {
if (i % k == 0) {
prime = false;
}
}
if (prime) {
myarray[j] = i;
if (j == 10000) {
System.out.println(myarray[10000]);
return;
}
j++;
}
if(i > 4)
i += 2;
else
i++;
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
In this code I wanted solve Project Euler Problem #3. The objective is to find the biggest prime number. My code is running right but there is a problem at runtime. How can I reduce run time? Can anyone suggest any tips?
public class Euler3 {
//https://www.hackerrank.com/contests/projecteuler/challenges/euler003
public static void main(String[] args) {
long[] inputs = readInputs();
for (int i = 0; i < inputs.length; i++) {
System.out.println(findBiggestPrime(inputs[i]));
}
}
public static boolean isPrime(long num) {
if (num == 2)
return true;
for (long i = 3; i * i <= num; i += 2) {
if (num % i == 0)
return false;
}
return true;
}
private static long[] readInputs() {
Scanner scanner = new Scanner(System.in);
int inputQuantities = scanner.nextInt();
long[] inputs = new long[inputQuantities];
for (int i = 0; i < inputQuantities; i++) {
inputs[i] = scanner.nextLong();
}
return inputs;
}
private static long findBiggestPrime(long number) {
long biggestPrime = 0;
if (number % 2 == 0) {
number = number / 2;
biggestPrime = 2;
}
if (number == 2)
return 2;
for (int i = 3; i <= number; i += 2) {
if (number % i != 0)
continue;
if(!isPrime(i))
continue;;
biggestPrime = i;
number = number / biggestPrime;
}
return biggestPrime;
}
}
The lines
if(!isPrime(i))
continue;
will slow down your algorithm and should not be there.
Any factor you encounter in your algorithm should automatically be prime. You should not, for example, ever encounter the factor 15 because you should have already encountered 3 and 5 and divided by them both.
To make this work you should not just do number = number / biggestPrime;. When you encounter a factor you should keep dividing by it until it no longer goes into the number. This way you clear out powers.
isPrime() is hugely inefficient. Here's a version that keeps track of already-confirmed-multiples in a HashSet. I don't know what order of magnitude of #'s you are using. This seems to work with some efficiency on my machine in the ~100K range.
private static final Set<Long> multiples = new HashSet<>();
private static boolean isPrime(long l) {
if(l%2==0 && l>2)
return false;
if(multiples.contains(l))
return false;
double r = Math.sqrt(l);
for(long i=3;i<=r;++i) {
for (long j = i * 2; j <= l; j += i) {
multiples.add(j);
if (j == l) {
return false;
}
}
}
return true;
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm new to Java and I'm trying to make an lvling system. Hers my code so far:
import java.util.*;
class Player
{
private String Name;
private int Level;
private int EXP;
int NextGoaltoLvl = 1000;
public Player(String n, int lvl, int xp)
{
Name = n;
Level = lvl;
EXP = xp;
}
public void printStats()
{
System.out.println("Name: " +Name);
System.out.println("Level: " +Level);
System.out.println("Exp: " + EXP);
}
public void addLevel(int addlvl)
{
Level += addlvl;
System.out.println("Congratulations,"+ Name +",you have leveled up to " + Level + "!");
}
public void addExp(int num)
{
EXP += num;
if (EXP == NextGoaltoLvl)
{
addLevel(1); NextGoaltoLvl += 1000; EXP = 0;
}
}
}
public class MainC
{
public static void main(String[] args)
{
Player Player01 = new Player("kert109",1,0);
for (int i = 0; i >= 10000; i++)
{
Player01.addExp(1);
}
Player01.printStats();
}
}
Player01.printStats();
I still having an error here. Says: Syntax error, insert "}" to complete ClassBody.
I have no idea whats wrong. Help? I have check ever "{" and "}". I have cleaned to code too. (Using Eclipse.)
Two errors I see:
1.
Near addExp, there is a while loop outside of the method, which is a syntax error. What's the purpose of this loop anyhow? It's an infinite loop without any breaks or returns in its body - is it actually supposed to go on forever?
2.
for (int i; i >= 10000; i++)
{
Player01.addExp(1);
}
You forgot to initialize i here. Although, this loop doesn't make sense, your condition asks if i is greater than something else and yet you increment it on each iteration (i++). What are you trying to do here?
Instead of
public void addExp(int num)
{
EXP += num;
}
while (true)
{
if (EXP == NextGoaltoLvl)
{
addLevel(1); NextGoaltoLvl += 1000; EXP = 0;
}
}
(an infinite loop? outside all function code? compile error + logic error)
I think you want
public void addExp(int num)
{
EXP += num;
if (EXP == NextGoaltoLvl)
{
addLevel(1); NextGoaltoLvl += 1000; EXP = 0;
}
}
(increment level if XP reaches new level XP)
A. R. S points out another serious issue with your for loop.
Instead of
for (int i; i >= 10000; i++)
{
You want
for (int i = 0; i <= 10000; i++)
{
or just
Player01.addExp(10000);
If what you want to do is to add 10000 XP to the player
you need to put the while loop inside of the method addExp and initialize i to 0 in one of your for loops
public void addExp(int num)
{
EXP += num;
while (true)
{
if (EXP == NextGoaltoLvl)
{
addLevel(1); NextGoaltoLvl += 1000; EXP = 0;
}
}
}
public static void main(String[] args)
{
Player Player01 = new Player("kert109",1,0);
for (int i=0; i >= 10000; i++)
{
Player01.addExp(1);
}
Player01.printStats();
}
1) For loop has an error because you have initiated int i without specifying it's initial value.
for( int i = yourInitialValue; i >= 10000; i++ )
2)
public void addExp(int num)
{
EXP += num;
}
while (true)
{
if (EXP == NextGoaltoLvl)
{
addLevel(1); NextGoaltoLvl += 1000; EXP = 0;
}
}
while loop is outside your addExp method. Where you might want it to be:
public void addExp(int num){
EXP += num;
while (true)
{
if (EXP == NextGoaltoLvl)
{
addLevel(1); NextGoaltoLvl += 1000; EXP = 0;
}
}
}
Your while loop isn't in a method. Here's a revised addExp method.
public void addExp(int num)
{
EXP += num;
if (EXP == NextGoaltoLvl)
{
addLevel(1); NextGoaltoLvl += 1000; EXP = 0;
}
}
You're also not initializing i in your main method. It's also important to note that i >= 10000 will always return false. Your for loop should probably be revised to:
for (int i = 0; i < 10000; i++)
{
Player01.addExp(1);
}