Project Euler #3 Java - java

public class Problem3 {
public static void main (String args[]) {
System.out.print(primeMod(60085147514L));
}
public static double primeMod(long d) {
long max = 0;
int count = 0;
for (long i = 2; i < d; i++) {
if (d % i == 0) {
boolean isPrime = primeCounter(i);
if(isPrime == true) {
max = i;
System.out.println(max);
}
} else {
max = max;
}
}
return max;
}
public static boolean primeCounter(long x) {
int count = 0;
for (int s = 1; s <= x; s++) {
if (x % s == 0) {
count++;
}
}
if (count == 2) {
return true;
} else {
return false;
}
}
}
My program works for smaller numbers but it Throws an Arthmetic Exception for Divide by 0 when its not dividing by zero.please dont give me the answer,just wanna understand it and improve my skills
thank you

My guess would be that s is overflowing, leading eventually to a divide by zero. Make s a long instead.

Related

coinFlip heads streak output

I'm supposed to flip a coin 100 times, and find out the longest streak of heads, then output it, but so far, it's only giving me how many heads there are in total. I've tried a bunch of things but can't find a solution.
public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 100;
public void run()
{
int h = 0;
int t = 0;
boolean wasHeads = false;
boolean isHeads = false;
int streak = 0;
int ih = 0;
for (int i = 0; i < FLIPS; i++) {
int coinFlip = Randomizer.nextInt(1, 2);
if (coinFlip == 2) {
System.out.println("Heads");
h++;
ih++;
isHeads = true;
if (ih > 1) {
wasHeads = true;
}
if ((isHeads = true) && (wasHeads = true)) {
streak++;
} else {
streak = 0;
}
} else if (coinFlip == 1) {
System.out.println("Tails");
t++;
isHeads = false;
ih = 0;
}
}
System.out.println(streak);
}
}
You need to substantially simplify your code.
public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 100;
public void run()
{
int wasHeads = 0;
int streak = 0;
int bestStreak = 0;
for (int i = 0; i < FLIPS; i++) {
int coinFlip = Randomizer.nextInt(1, 2);
if (coinFlip == 2) {
streak++;
wasHeads = 1;
} else if (coinFlip == 1) {
wasHeads = 0;
if (steak > bestStreak) {
bestStreak = streak;
}
streak = 0;
}
}
System.out.println(streak);
}
}
Reset streak when it ends (coinFlip is 1), but first check if it's better than your best streak before then, updating the bestStreak if so accordingly. Otherwise, just iterate streak and keep wasHeads at 1 for each head. Note there's not need for a boolean here; a 1 or 0 integer is literally and logically the same thing.
You can simplify your code a bit, wasHeads and isHeads are not really needed. Also, more descriptive variable names makes your code easier to understand. So, something like this:
public void run() {
int highestNumberOfConsecutiveHeads = 0;
int currentNumberOfConsecutiveHeads = 0;
for (int i = 0; i < 100; i++) {
if (Randomizer.nextInt(1, 2) == 2) {
currentNumberOfConsecutiveHeads++;
if (currentNumberOfConsecutiveHeads > largestNumberOfConsecutiveHeads) {
highestNumberOfConsecutiveHeads = currentNumberOfConsecutiveHeads;
}
} else {
currentNumberOfConsecutiveHeads = 0;
}
}
System.out.println("Longest streak: " + highestnumberOfConsecutiveHeads);
}
First and foremost, fix your line here so it's easier to read: }} else if (coinFlip == 1) {
(You need a newline between those two close braces)
I would consider setting up some more clear variable names. For example: totalHeads, totalTails. I'm not quite getting what your ih variable is SUPPOSED to be, but the variable names I would use for solving this problem are thisStreak and bestStreak. is/washeads should be unnecessary. I think that should be enough of a push to get you to a solution.
Thanks for the help, fixed my code :)
public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 100;
public void run()
{
int h = 0;
int t = 0;
boolean wasHeads = false;
boolean isHeads = false;
int longest = 0;
int streak = 0;
int ih = 0;
for (int i = 0; i < FLIPS; i++) {
int coinFlip = Randomizer.nextInt(1, 2);
if (coinFlip == 2) { //heads
System.out.println("Heads");
if (wasHeads = true) {
streak++;
} else {
streak = 0;
}
wasHeads = true;
} else if(coinFlip == 1) { //tails
System.out.println("Tails");
t++;
isHeads = false;
if (streak > longest){
longest = streak;
}
streak = 0;
ih = 0;
}
}
System.out.println("Longest streak of heads: " + longest);
}
}

The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143?

My program is not working on eclipse.. And i dont know whats wrong with it..
Plz help..
And plz tell the reason as well.
public class ProblemThree {
public static void main(String args[])
{
long a=0L, z=0L;
long n=600851475143L;
for(long i=2;i<=n ;++i)
{
if(600851475143L % i==0)
{
a=i;
if(a%2==0)
{; }
else if(a%3==0)
{ ;}
else if(a%5==0)
{ ;}
else if(a%7==0)
{ ;}
else if (a>z)
{
z=a;
}
}
}
System.out.println(z);
}
}
Thank you guys for your feedback but i have solved this question myself with the following code.. :)
public class ProblemThree {
public static void main(String args[])
{
long n=600851475143L;
for(long i=2;i<n ;++i)
{
while(n % i==0)
{//for yes
n=n/i;
}
}
System.out.println(n);
}
}
Your program isn't "returning" anything because it is still running. Your loop is still iterated. Your code needs to be modified to be more performant. Here is my solution to the same problem.
long testNum = 600851475143l;
int largestFactor = 0;
long loopMax = 17425170l; //largest known prime
for (int i = 3; i * i <= loopMax; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime && testNum % i == 0) {
System.out.println("prime factor: " + i);
largestFactor = i;
loopMax = (testNum / i) + 1;
}
}
System.out.println("result is: " + largestFactor);
package Euler;
import java.util.Scanner;
public class euler3 {
public static void main(String args[])
{
long num;
Scanner sc = new Scanner(System.in);
num= sc.nextLong();
for(int i=2;i<num; i++)
{
while(num%i == 0)
{
//System.out.println(i);
num=num/i;
}
}
if(num>2)
System.out.println(num);
}
}
The prime factors of 13195 are 5, 7, 13 and 29.
The largest prime factor of the number 600851475143 is 6857.
#include <bits/stdc++.h>
using namespace std;
int SieveOfEratosthenes(int x,long long signed int n)
{
bool prime[x]; //use sieve upto square root of
// required number
memset(prime, true, sizeof(prime));
for (long long signed int p = 2; p * p <= x; p++)
{
if (prime[p] == true)
{
for (long long signed int i = p * p; i <= x; i += p)
prime[i] = false;
}
}
int res;
for (long long signed int p = 2; p <= x; p++)
if (prime[p])
{
if(n%p==0) //if number is divisble by prime number than update with
res=p; //latest value of prime number
}
return res;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout<<SieveOfEratosthenes(775146,600851475143);//Return the answer
// long long signed int n;cin>>n; for value of n
//cout<<SieveOfEratosthenes(sqrt(n),n);
return 0;
}

Why is my method repeating when I run

public class PalindromicPrimes {
public static void main (String[] args) {
userInt();
System.out.println("The palindromic primes less than " + userInt() +
" are:");
for (int i = 0; i <= userInt(); i++) {
if (isPrime() && isPalindrome()) {
System.out.println(i);
}
}
}
private static boolean isPrime() {
if (userInt() == 2 || userInt() == 3) {
return true;
}
if (userInt() % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(userInt()) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (userInt() % i == 0) {
return false;
}
}
return true;
}
private static boolean isPalindrome() {
if (userInt() < 0)
return false;
int div = 1;
while (userInt() / div >= 10) {
div *= 10;
}
while (userInt() != 0) {
int x = userInt();
int l = x / div;
int r = x % 10;
if (l != r)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
private static int userInt() {
Scanner s = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int userInt = s.nextInt();
return userInt;
}
}
is there a different way of getting the user input? or can I keep it this way?
when it runs it just keeps prompting the user input.
rearrange it like this:
public static void main (String[] args) {
//get it and save it here!
int userValue = userInt();
System.out.println("The palindromic primes less than " + userValue +
" are:");
for (int i = 0; i <= userValue; i++) {
if (isPrime(userValue) && isPalindrome(userValue)) {
System.out.println(i);
}
}
}
then also update all the methods that care about this "userInt" value.
Every time you call userInt() you're telling the code to get a new value from the command line.
Try this:
public static void main (String[] args) {
int value = userInt();
System.out.println("The palindromic primes less than " + value +
" are:");
for (int i = 0; i <= value; i++) {
if (isPrime() && isPalindrome()) {
System.out.println(i);
}
}
}
The term userInt() is a function invocation that prompts the user for input. Odds are you only want to do this once. You're doing it multiple times.
You should store the result of userInt() in a variable.
int typed = userInt();
And then use this variable to reference what the user typed instead of calling userInt() again.
System.out.println("The palindromic primes less than " + typed +
" are:");
for(int i = 0; i < typed; i++) ...
You keep calling userInt(). That is the problem.
I don't understand your logic. So I have not modified that code. But the code runs.
import java.util.Scanner;
public class PalindromicPrimes {
public static void main (String[] args) {
int x = userInt();
System.out.println("The palindromic primes less than " + x +
" are:");
for (int i = 0; i <= x; i++) {
if (isPrime(i) && isPalindrome(i)) {
System.out.println(i);
}
}
}
private static boolean isPrime(int a) {
if (a == 2 || a == 3) {
return true;
}
if (a % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(a) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (a % i == 0) {
return false;
}
}
return true;
}
private static boolean isPalindrome(int a) {
if (a < 0)
return false;
int div = 1;
while (a / div >= 10) {
div *= 10;
}
while (a != 0) {
int x = a;
int l = x / div;
int r = x % 10;
if (l != r)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
private static int userInt() {
Scanner s = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int userInteger = s.nextInt();
return userInteger;
}
}
Remember, don't use the same names for variable and function. In the function userInt(), you have used a variable int userInt, to get the result from the scanner. This might be aa recursive call sometimes. Be careful with that.

Largest prime factor program takes aaaages - Java

So this is problem 3 from project Euler. For those who don't know, I have to find out the largest prime factor of 600851475143. I have the below code:
import java.lang.Math;
// 600851475143
public class LargestPrimeFactor {
public static void main(String[] stuff) {
long num = getLong("What number do you want to analyse? ");
long[] primes = primeGenerator(num);
long result = 0;
for(int i = 0; i < primes.length; i++) {
boolean modulo2 = num % primes[i] == 0;
if(modulo2) {
result = primes[i];
}
}
System.out.println(result);
}
public static long[] primeGenerator(long limit) {
int aindex = 0;
long[] ps = new long[primeCount(limit)];
for(long i = 2; i < limit + 1; i++) {
if(primeCheck(i)) {
ps[aindex] = i;
aindex++;
}
}
return ps;
}
public static boolean primeCheck(long num) {
boolean r = false;
if(num == 2 || num == 3) {
return true;
}
else if(num == 1) {
return false;
}
for(long i = 2; i < Math.sqrt(num); i++) {
boolean modulo = num % i == 0;
if(modulo) {
r = false;
break;
}
else if(Math.sqrt(num) < i + 1 && !modulo) {
r = true;
break;
}
}
return r;
}
public static int primeCount(long limit) {
int count = 0;
if(limit == 1 || limit == 2) {
return 0;
}
for(long i = 2; i <= limit; i++) {
if(primeCheck(i)) {
count++;
}
}
return count;
}
public static long getLong(String prompt) {
System.out.print(prompt + " ");
long mrlong = input.nextLong();
input.nextLine();
return mrlong;
}
}
But when I test the program with something (a lot) smaller than 600851475143, like 100000000, then the program takes its time - in fact, 100000000 has taken 20 minutes so far and is still going. I've obviously got the wrong approach here (and yes, the program does work, I tried it out with smaller numbers). Can anyone suggest a less exhaustive way?
public static void main(String[] args) {
long number = 600851475143L;
long highestPrime = -1;
for (long i = 2; i <= number; ++i) {
if (number % i == 0) {
highestPrime = i;
number /= i;
--i;
}
}
System.out.println(highestPrime);
}
public class LargestPrimeFactor {
public static boolean isPrime(long num){
int count = 0;
for(long i = 1; i<=num/2 ; i++){
if(num % i==0){
count++;
}
}
if(count==1){
return true;
}
return false;
}
public static String largestPrimeFactor(long num){
String factor = "none";
for(long i = 2; i<= num/2 ; i++){
if(num % i==0 && isPrime(i)){
factor = Long.toString(i);
}
}
return factor;
}
public static void main(String[] args) {
System.out.println(largestPrimeFactor(13195));
}
}
I have done several dozen of the challenges on Project Euler. Some of the questions can be solved with brute force (they recommend not to do this) but others require "out of the box" thinking. You cannot solve that by problem with brute force.
There is lots of help on the web to lead you in the right direction, for example:
http://thetaoishere.blogspot.com.au/2008/05/largest-prime-factor-of-number.html
The number of prime factors a number can have is always less than sqrt of that number so that there is no need to iterate through the number n to find its largest prime factor.
See this code.
public class LargestPrimeFactor {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
long num=sc.nextLong();
if(num>0 && num<=2)
{
System.out.println("largest prime is:-" + num);
System.exit(0);
}
int i=((Double)Math.sqrt(num)).intValue();
int j=3;
int x=0;
//used for looping through the j value which can also be a prime. for e.g in case of 100 we might get 9 as a divisor. we need to make sure divisor is also a prime number.
int z=0;
//same function as j but for divisor
int y=3;
int max=2;
//divisor is divisible
boolean flag=false;
//we found prime factors
boolean found=false;
while(x<=i)
{
y=3;
flag=false;
if(num % j ==0)
{
if(j>max)
{
for(z=0;z<Math.sqrt(j);z++)
{
if(j!=y && j % y==0)
{
flag=true;
}
y+=2;
}
if(!flag)
{
found=true;
max=j;
}
}
}
j+=2;
x++;
}
if(found){
System.out.println("The maximum prime is :- " + max);
}
else
{
System.out.println("The maximum prime is :- " + num);
}
}
}
change
for(long i = 2; i <= limit; i++)
to
// add the one for rounding errors in the sqrt function
new_limit = sqrt(limit) + 1;
// all even numbers are not prime
for(long i = 3; i <= new_limit; i+=2)
{
...
}
Factoring 1,000,000 for example instead of iterating 1,000,000 times
the thing only needs to do around 500 iterations.

Problems with the N queen homework exercice in Java

I'm using my own implementation of the stack.
I should not use recursion.
My code:
public static void solve(int bsize)
{
stack queenLoc = new stack();
int y=0;
int count=0;
boolean done = false;
while(done == false && queenLoc.size() != bsize)
{
queenLoc.push(count);
if(!isSafe(bsize,queenLoc,count))
{
while(queenLoc.getTop() == bsize)
{
y = queenLoc.pop();
count--;
}
if(queenLoc.top != null)
{
queenLoc.push(queenLoc.pop()+1);
count++;
}
else
{
queenLoc.push(y+1);
count++;
}
}
else if(queenLoc.size() == bsize)
{
done = true;
}
else
{
count++;
queenLoc.push(count);
}
}
queenLoc.showAll();
if(queenLoc.size() == bsize)
printBoard(bsize, queenLoc);
}
public static boolean isSafe(int bsize, stack s,int count)
{
for(int i = 1; i<s.size(); i++)
{
if(s.getTop() == s.get(i) || s.getTop()+count == s.get(i)+s.size() || s.getTop()-count == s.get(i)-s.size())
return false;
}
return true;
}
I'm not sure what is really going on, i'm getting wrong position and the printBoard function is only printing the queens on the first row.
I actually tried a lot of possibilities, but i got a bit confused.
Can anyone just point me out to the right direction and tell me where's the problem in my code. I am using the stack to store the column and the "count" variable in the stack class to point me to which row.
package mynqueens;
public class MyNQueens {
public static int board[][] = new int[4][4];
public static int row,column;
public MyNQueens(){
}
public static void main(String[] args) {
check(0,0);
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(board[i][j] + "\t");
}
System.out.println();
}
}
public static void check(int i, int j ){
while(i<3){
board[i][j] = 1;
i++;
}
while(i!=0){
board[i][j] = 1;
i--;
}
while(j<3){
board[i][j]=1;
j++;
}
while(j!=0){
board[i][j] = 1;
j--;
}
while(j<3 || i<3){
board[i][j] = 1;
i++;
j++;
}
while(j!=0 || i!=0){
board[i][j] = 1;
i--;
j--;
}
while(i<3 || j!=0){
board[i][j]=1;
i++;
j--;
}
while(i!=0 || j<3){
board[i][j]=1;
i--;
j++;
}
}
}
Before you start erasing elements in inner while section
while(queenLoc.getTop() == bsize)
{
y = queenLoc.pop();
count--;
}
number of elements in queenStack will exceed bsize.
You have while(done == false && queenLoc.size() != bsize) so when size of queenLoc will be equal to bsize you will print result.
What I am saying is that after bsize steps you are always printing results.
Advise: Your code should have invariant "queenLoc represents position where no two queens attack each other".
import java.util.Scanner;
/**
*
* #author Manimekalai
*/
public class Queen {
public static boolean isConsistent(int[] q, int n)
{
for (int i = 0; i < n; i++)
{
if (q[i] == q[n]) return false; // same column
if ((q[i] - q[n]) == (n - i)) return false; // same major diagonal
if ((q[n] - q[i]) == (n - i)) return false; // same minor diagonal
}
return true;
}
public static void printQueens(int[] q)
{
int N = q.length;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (q[i] == j) System.out.print("Q ");
else System.out.print("* ");
}
System.out.println();
}
System.out.println();
}
public static void enumerate(int N)
{
int[] a = new int[N];
enumerate(a, 0);
}
public static void enumerate(int[] q, int n)
{
int N = q.length;
if (n == N) printQueens(q);
else
{
for (int i = 0; i < N; i++)
{
q[n] = i;
if (isConsistent(q, n)) enumerate(q, n+1);
}
}
}
public static void main(String[] args)
{
//int N = Integer.parseInt(args[0]);
System.out.println("Enter N value");
Scanner s=new Scanner(System.in);
int N=s.nextInt();
enumerate(N);
}
}

Categories