trying to find the sum of even fibonacci numbers to 4 million - java

I am trying to find the sum of the even Fibonacci numbers up untill 4 million.
I found the numbers but i can't get them add up... in the if(n % 2 ==0) loop
8
34
144
610
2584
10946
46368
196418
832040
3524578
public static void number2()
{
int number = 40;
int a, b, c;
int numLim = 0;
a = 1;
b = 2;
while(numLim < 4000000)
{
c = a + b;
a = b;
b = c;
numLim = b;
if(numLim > 4000000)
{
break;
}
int sum = 0;
if(numLim % 2 == 0)
{
System.out.println(numLim);
sum = sum + numLim;
System.out.println("sum :" +sum);
}
}
}

You must define sum outside the while loop, or it will become 0 each iteration.
int sum = 0;
...
while ...
Remember not to set sum to 0 each iteration.

public class Euler2 {
public static void main(String[] args) {
int fibonacci;
int num = 0;
int num2 = 1;
int loop;
int sum = 0;
System.out.println(num2);
for (loop = 0; loop <= 32; loop++) {
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
System.out.println("Fibonacci number : " + fibonacci);
sum += fibonacci;
System.out.println("This is the sum " +sum);
}
}
}
So I solved it like this, it's a little more efficient and the math works but Euler hates me, hope this helps.

public class Euler2 {
public static void main(String[] args) {
int fibonacci;
int num = 0;
int num2 = 1;
int loop;
int sum = 0;
System.out.println(num2);
for (loop = 0; loop <= 31; loop++) {
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
System.out.println("Fibonacci number : " + fibonacci);
if (fibonacci%2 == 0) {
sum += fibonacci;
System.out.println(sum);
}
}
}
Sorry, this code works.

Tried doing the above in Java and here is my solution that works
public static void main(String[] args) {
int first = 1;
int second = 2;
int sum = 0;
int sumOfEvenValuedTerms = second;
for (int i = 0; i < 30; i++) {
sum = first + second;
if (sum <= 4000000) {
if (sum % 2 == 0) {
sumOfEvenValuedTerms += sum;
}
first = second;
second = sum;
}
}
System.out.println(sumOfEvenValuedTerms);
}
Output is 4613732

public static int getSumOfEvenNumbers(int n) {
int prev = 0;
int i =1;
int sum = 0;
while (i<n){
int nextNumber = i + prev;
if(nextNumber %2 ==0) {
System.out.println(nextNumber);
sum +=nextNumber;
}
prev = i;
i = nextNumber;
}
return sum;
}

public class evenFib {
public static void main(String[] args) {
double a = 1, b = 2, c = 0, sum = 0;
for (double i = 0; i <= 1000; i++) {
c = a + b;
a = b;
b = c;
if (c % 2 == 0 && sum < 4000000) {
sum = sum + c;
}
}
System.out.println(sum + 2);
}
}

Related

Why does my loop increment 1 over the value needed?

This is my first CS class ever, and I'm trying to learn everything the best that can. In this loop I am trying to find valid mastercard numbers using Luhn's formula. The program works, but it's been bugging me that my final for loop outputs 1 number over the correct value, unless I subtract 1 from z after the loop finishes iterating. For example: if the sum = 56 , then z would = 5 , when the correct answer would be 4. How can I fix this going forward?
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class MCGenerator {
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
Random rand = new Random();
System.out.print("How many Mastercard numbers would you like to generate? ");
int quantity = scnr.nextInt();
int x;
int use;
int range;
int appendI;
Long appendL;
String firstDigits;
String append;
String preliminary;
int y;
int c;
int sum;
int z;
int findDigit;
String lastNum;
String cardNumber;
System.out.println("\nHere you go, have fun: ");
for(x = 0; x < quantity; x++ ) {
use = rand.nextInt(2 - 1 + 1) +1;
if(use == 1) {
range = rand.nextInt(55 - 51 + 1) + 51;
}
else {
range = rand.nextInt(272099 - 222100 +1) + 222100;
}
if(range < 56) {
appendL = ThreadLocalRandom.current().nextLong(1000000000000L, 10000000000000L);
append = String.valueOf(appendL);
}
else {
appendI = rand.nextInt(999999999 - 100000000 + 1) + 100000000;
append = String.valueOf(appendI);
}
firstDigits = String.valueOf(range);
preliminary = firstDigits + append;
for(y = 0, sum = 0; y < 15; y++ ) {
c = preliminary.charAt(y) - '0';
if(y % 2 == 0){
c *= 2;
}
if(c > 9) {
c -= 9;
}
sum += c;
}
for(z = 0, findDigit = sum; findDigit > 0; z++){
findDigit = sum + z;
findDigit %= 10;
}
z -= 1;
lastNum = String.valueOf(z);
cardNumber = preliminary + lastNum;
System.out.println(cardNumber);
}
}
}

fibonacci and prime numbers in one series

I am trying to do some mock questions of coding for an entrance exam, I came about this question and I am stuck at the PRIME NUMBERS part.
Here is the question:
Consider the below series: 1, 2, 1, 3, 2, 5, 3, 7, 5, 11, 8, 13, 13, 17, … This series is a mixture of 2 series – all the odd terms in this series form a Fibonacci series and all the even terms are the prime numbers in ascending order. Write a program to find the Nth term in this series. For example, when N = 14, the 14th term in the series is 17. So only the value 17 should be printed out.
public class OandF {
// main
public static void main(String[] args) {
System.out.println(dofibo(9));
}
public static int dofibo(int m) {
if(m == 0) {
return 0;
}
if(m == 1) {
return 1;
}
return dofibo(m-1) + dofibo(m-2);
}
}
// as you can see this is where I got to, and I don't know how to proceed
There are multiple ways to find the nth Prime number, the easiest way is to keep counting the prime numbers from 1 to n. But this is very time consuming otherwise refer to Fermat's theorems or Sieve of Eratosthenes.
private boolean isPrime(int n) {
if (n == 2 || n == 3) return true;
for(int i = 2; i < (int)Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public int nthPrime(int n) {
int number, primeCount;
for(number = 2, primeCount = 0; primeCount < n; number++) {
if (isPrime(number)) {
++primeCount;
}
}
return number;
}
You can try this, it may solve your problem.
class FibonacciExample1 {
public static void main(String args[]) {
int input = 20;
fibonacci(input);
System.out.print("-----------------------------");
prime(input);
}
public static void fibonacci(int input) {
int n1 = 0, n2 = 1, n3, i, count = input;
System.out.print(n1 + " " + n2);
for (i = 2; i < count; ++i) {
n3 = n1 + n2;
System.out.print(" " + n3);
n1 = n2;
n2 = n3;
}
}
public static void prime(int input) {
int i = 0;
int num = 0;
String primeNumbers = "";
for (i = 1; i <= input; i++) {
int counter = 0;
for (num = i; num >= 1; num--) {
if (i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println(primeNumbers);
}
}
I'd make these two programs into simpler, infinite generators that are easier to debug and then sequence:
import java.util.ArrayList;
class Fibonacci {
int a = 0, b = 1;
int next() {
int c = a;
a = b;
b += c;
return a;
}
}
class Prime {
ArrayList<Integer> primes = new ArrayList<>();
int number = 2;
int next() {
if (number == 2) { // special case
primes.add(number);
number = 1;
return 2;
}
outer: while (true) {
number += 2;
for (int divisor: primes) {
if (divisor * divisor > number) {
break outer;
}
if (number % divisor == 0) {
break;
}
}
}
primes.add(number);
return number;
}
}
public class Example {
public static int sequence(int n) {
int nth = -1;
if ((n % 2) == 0) {
Fibonacci fibonacci_generator = new Fibonacci();
for (int i = 0; i < (n / 2) + 1; i++) {
nth = fibonacci_generator.next();
}
} else {
Prime prime_generator = new Prime();
for (int i = 0; i < (n + 1) / 2; i++) {
nth = prime_generator.next();
}
}
return nth;
}
public static void main(String args[]) {
System.out.println(sequence(13)); // 14th element counting from zero
}
}

Armstrong number in Java

This is my code, it is not producing any output. As I have started my loop from 100 so according to the logic used I should get answer as 153. But nothing is coming. Please help.
// Program to find the first Angstrom Number and display it!
public static void main(String[] args) {
int sum = 0;
int y, z;
System.out.println("Starting program");
for (int i = 100; i < 1000; i++) {
sum += (i % 10) * (i % 10) * (i % 10);
y = i / 10;
sum += (y % 10) * (y % 10) * (y % 10);
z = y / 10;
sum += z * z * z;
if (sum == i) {
System.out.println("The first Angstrom number is " + i);
break;
}
}
}
You should reset the sum in every step:
for (int i = 100; i < 1000; i++) {
sum = 0;
sum += (i%10) * (i%10) * (i%10);
....
}
You can find Armstrong number between two numbers by using this logic. Just change the values according to you need.
public class Armstrong {
public static void main(String[] args) {
int low = 999, high = 99999;
for(int number = low + 1; number < high; ++number) {
int digits = 0;
int result = 0;
int originalNumber = number;
// number of digits calculation
while (originalNumber != 0) {
originalNumber /= 10;
++digits;
}
originalNumber = number;
// result contains sum of nth power of its digits
while (originalNumber != 0) {
int remainder = originalNumber % 10;
result += Math.pow(remainder, digits);
originalNumber /= 10;
}
if (result == number)
System.out.print(number + " ");
}
}
}
Output of this program is:
1634 8208 9474 54748 92727 93084
public static int Power(int out,int res)
{
int count=res;
int temp=1;
while(count!=0)
{
temp=temp*out;
count--;
}
return temp;
}
public static int count1(int num)
{
int count=0;
while(num!=0)
{
num=num/10;
count++;
}
return count;
}
public static int isArmstrong(int num)
{
int out;
int sum=0;
int res=count1(num);
while(num!=0)
{
out=num%10;
sum=sum+Power(out,res);
num=num/10;
}
return sum;
}
public static void main(String[] args)
{
int start=10;
int end=100000;
for(int i=start;i<=end;i++)
{
int result=isArmstrong(i);
if(result==i)
{
System.out.println(i);
}
public class armstrongNumber
{
public void isArmstrong(String n)
{
char[] s=n.toCharArray();
int size=s.length;
int sum=0;
for(char num:s)
{int temp=1;
int i=Integer.parseInt(Character.toString(num));
for(int j=0;j<=size-1;j++)
{ temp *=i;}
sum +=temp;
}
if(sum==Integer.parseInt(n))
{
System.out.println(n+" is an Armstrong Number");
}
else
{
System.out.println(n+" is not an Armstrong Number");
}
}
public static void main(String[] args)
{
armstrongNumber am= new armstrongNumber();
am.isArmstrong("2");
am.isArmstrong("153");
am.isArmstrong("1634");
am.isArmstrong("231");
}
}
public class Armstrong {
public static int findArmStrong(int x, int y) {
if(x== getArmstrongSum(x)) return x;
else if(y== getArmstrongSum(y)) return y;
else return -1;
}
public static int getArmstrongSum(int num) {
int pow = String.valueOf(num).length();
return IntStream.iterate(num, i -> i / 10)
.limit(pow)
.map(i -> (int) Math.pow(i % 10, 3))
.sum();
}
public static void main(String[] args) {
System.out.println(findArmStrong(153, 154));
}
}

Why doesn't my program run correctly?

for my school project I have to create a program that outputs perfect numbers based on how many perfect numbers the user(teacher) want. The user can pick any number from 1-4 and it should display however many number the user chooses. Here is my current code. Please ignore the sumupTo, factorial, isprime, and the testGoldbach methods, please only look at the Perfect numbers method/code.
import java.util.Scanner;
public class MyMathB
{
public static int sumUpTo(int n)
{
int sum = 0;
for (int k = 1; k <= n; k++)
sum += k;
return sum;
}
public static long factorial(int n)
{
long f = 1;
for (int k = 2; k <= n; k++)
f *= k;
return f;
}
public static boolean isPrime(int n)
{
if (n <= 1)
return false;
int m = 2;
while (m * m <= n)
{
if (n % m == 0)
return false;
m++;
}
return true;
}
public static void PerfectNumbers(int number)
{
System.out.println("How many perfect numbers would you like to see? Please enter an integer from 1 to 4");
Scanner s = new Scanner(System.in);
int numbersToSee = s.nextInt();
int counts = 0;
for(counts = 0; counts <= numbersToSee; counts++)
{
for (int n = 5; n <= 10000; n++)
{
int temp = 0;
for(int i = 1; i <= number / 2; i++)
{
if (number % i == 0)
{
temp += i;
}
if (temp == number)
{
System.out.println(number);
}
}
}
}
}
public static boolean testGoldbach(int bigNum)
{
for (int n = 6; n <= bigNum; n += 2)
{
boolean found2primes = false;
for (int p = 3; p <= n/2; p += 2)
{
if (isPrime(p) && isPrime(n - p))
found2primes = true;
}
if (!found2primes)
{
System.out.println(n + " is not a sum of two primes!");
return false;
}
}
return true;
}
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int n;
do
{
System.out.print("Enter an integer from 4 to 20: ");
n = kb.nextInt();
} while (n < 4 || n > 20);
kb.close();
System.out.println();
System.out.println("1 + ... + " + n + " = " + sumUpTo(n));
System.out.println(n + "! = " + factorial(n));
System.out.println("Primes: ");
for (int k = 1; k <= n; k++)
if (isPrime(k))
System.out.print(k + " ");
System.out.println();
System.out.println("Goldbach conjecture up to " + n + ": " + testGoldbach(n));
}
}
you didn't declare the variable "number" in your method.
Edit: you didn't SET the variable number to anything, I misworded my last statement.

Prime Numbers III Problem 18 - I dont get the right answer even though I think I am right

I am new here. I am trying to solve this exercise Problem 18 just for reinforcing my solving skills. I've already coded the answer. The task asks for "How many of the primes below 1,000,000 have the sum of their digits equal to the number of days in a fortnight?" (a fortnight is 14 days). My answers is 16708, but it is wrong. I hope you can help me. I don't know what my error is. I have 2 methods, 1 for generating the primes, and another for counting the digits of each prime.
This is my code:
import java.util.ArrayList;
import java.util.List;
public class Problema18 {
public static void main(String args[]) {
ArrayList<Integer> num = primes();
System.out.println(num);
count(primes());
}
public static ArrayList<Integer> primes() {
List<Integer> primes = new ArrayList<Integer>();
primes.add(2);
for (int i = 3; i <= 1000000; i += 2) {
boolean isPrime = true;
int stoppingPoint = (int) (Math.pow(i, 0.5) + 1);
for (int p : primes) {
if (i % p == 0) {
isPrime = false;
break;
}
if (p > stoppingPoint) { break; }
}
if (isPrime) { primes.add(i); }
}
// System.out.println(primes);
return (ArrayList<Integer>) primes;
//System.out.println(primes.size());
}
public static void count(ArrayList<Integer> num) {
int count = 0;
for (int i = 0; i <= num.size() - 1; i++) {
int number = num.get(i);
String num1 = String.valueOf(number);
int sum = 0;
for (int j = 0; j < num1.length(); j++) {
sum = Integer.parseInt(num1.charAt(j) + "") + sum;
if (sum == 14) { count++; }
}
System.out.println(sum);
}
System.out.println(count);
}
}
You should check whether sum == 14 outside the inner for loop. What happens now is that you also count those primes for which the sum of digits is larger than 14 but the sum of the digits in some prefix of the prime is equal to 14.
This part...
if (sum == 14) {
count++;
}
should be outside the inner for-loop - i.e. you want to do it each time you pass through the i for-loop, but not each time you pass through the j for-loop.
Like this:
public static void count(ArrayList<Integer> num) {
int count = 0;
for (int i = 0; i <= num.size() - 1; i++) {
int number = num.get(i);
String num1 = String.valueOf(number);
int sum = 0;
for (int j = 0; j < num1.length(); j++) {
sum = Integer.parseInt(num1.charAt(j) + "") + sum;
}
System.out.println(sum);
if (sum == 14) {
count++;
}
}
System.out.println(count);
}

Categories

Resources