Showing posts with label method. Show all posts
Showing posts with label method. Show all posts

Project Euler > Problem 46 > Goldbach's other conjecture (Java Solution)

Problem:

It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.

9 = 7 + 2[×]12
15 = 7 + 2[×]22
21 = 3 + 2[×]32
25 = 7 + 2[×]32
27 = 19 + 2[×]22
33 = 31 + 2[×]12

It turns out that the conjecture was false.

What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?


Solution:

5777


Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
 * Solution to Project Euler problem 46
 * By Nayuki Minase
 * 
 * http://nayuki.eigenstate.org/page/project-euler-solutions
 * https://github.com/nayuki/Project-Euler-solutions
 */


public final class p046 implements EulerSolution {
 
 public static void main(String[] args) {
  System.out.println(new p046().run());
 }
 
 
 public String run() {
  for (int i = 2; ; i++) {
   if (!satisfiesConjecture(i))
    return Integer.toString(i);
  }
 }
 
 
 private boolean satisfiesConjecture(int n) {
  if (n % 2 == 0 || isPrime(n))
   return true;
  
  // Now n is an odd composite number
  for (int i = 1; i * i * 2 <= n; i++) {
   if (isPrime(n - i * i * 2))
    return true;
  }
  return false;
 }
 
 
 private boolean[] isPrime = {};
 
 private boolean isPrime(int n) {
  if (n >= isPrime.length)
   isPrime = Library.listPrimality(n * 2);
  return isPrime[n];
 }
 
}
Read More

Java > Warmup-1 >sleepIn (CodingBat Solution)

Problem:

The parameter weekday is true if it is a weekday, and the parameter vacation is true if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return true if we sleep in.

sleepIn(false, false) → true
sleepIn(true, false) → false
sleepIn(false, true) → true


Solution:

public boolean sleepIn(boolean weekday, boolean vacation) {
boolean DONE = false;
if (!weekday || vacation)
DONE = true;
  return DONE;
}
}
Read More

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact