How to print a variable as defined in a method? - java

public class Program {
public static void main(String[] args) {
int lastFibo = 1; // ADDED TO check if last fib calculated is over 4000000
for (int i = 3; lastFibo <= 4000000; i = i + (i - 1)) {
lastFibo = fibo(i);
}
}
public static int fibo(int i) {
int total = 0;
if (i % 2 == 0) {
total += i;
return total;
}
return total;
}
}
The purpose of this code is to print the sum of even numbers in the fibonacci sequence who's values are less than 4 million. Using recursion the code returns a stack overflow error so it was recommended to iterate through the numbers. The difficulty encountered was knowing how to print the "total" variable. Scope articles are very basic and creating a static int total = 0 would return 0.

First, as pointed out by some comments: your for loop will not iterate the Fibonacci sequence. Second, the variable total exists only in the scope of your fibo method. So every time the method is called, total starts with the value 0.
Use the correct Fibonacci algorithm and add the return value of the fibo method up to calculate the sum:
public class Program {
public static void main(String[] args) {
int total = 0;
int previousValue = 0;
int currentValue = 1;
while (currentValue < 4_000_000) {
int nextPreviousValue = currentValue;
currentValue += previousValue;
previousValue = nextPreviousValue;
total += fibo(currentValue);
}
System.out.println(total);
}
public static int fibo(int i) {
if (i % 2 == 0) {
return i;
}
return 0;
}
}
4_000_000 is an integer literal you can use since Java 7 for the number 4000000. The purpose of the underscores is to make it better readable for humans. Programmatically there is no difference to using 4000000. For details see Primitive Data Types in The Java Tutorials.

Note: This first part of the question was related to a misunderstanding. I supposed that it was necessary to calculated up to fib(4000000).
You must use BigInteger otherwise you can't handle so big numbers. It is a number with many thousands of digits!
fib(4000000) results in a number with over 835k digits. It is not possible to handle it with int or long.
The class BigInteger (or the equivalent BigDecimal for decimal values) borns to handle such kind of problems.
Note: this is the answer to the question
Now that the question is more clear it is possible to give the correct answer.
public void printEvenFib() {
int i = 1;
int lastFib = 1;
int sum = 0;
while (lastFib <= 4000000) {
if (lastFib % 2 == 0) {
sum += lastFib;
}
i++;
lastFib = fib(i);
}
System.out.println(sum);
}
// Without recursion
public int fib(int n) {
if (n <= 2) {
return 1;
}
int fibo1 = 1;
int fibo2 = 1;
int fibo = 0;
for (int i = 3; i <= n; i++) {
fibo = fibo1 + fibo2;
fibo2 = fibo1;
fibo1 = fibo;
}
return fibo;
}

class Program2{
public static void main(String args[]){
int n1=0,n2=1,n3,total=0,i;
for(i=1;n3<4000000;++i){
n3=n1+n2;
if(n3%2==0)
total+=n3;
n1=n2;
n2=n3;
}
System.out.println("total is "+total);
}
}

Related

Number trailing zeros in factorial in java

import java.util.Scanner;
import java.io.*;
class factorial {
void fact(int a) {
int i;
int ar[] = new int[10000];
int fact = 1, count = 0;
for (i = 1; i <= a; i++) {
fact = fact * i;
}
String str1 = Integer.toString(fact);
int len = str1.length();
i = 0;
do {
ar[i] = fact % 10;
fact /= 10;
i++;
} while (fact != 0);
for (i = 0; i < len; i++) {
if (ar[i] == 0) {
count = count + 1;
}
}
System.out.println(count);
}
public static void main(String...ab) {
int a;
Scanner input = new Scanner(System.in);
a = input.nextInt();
factorial ob = new factorial();
ob.fact(a);
}
}
This code is work up to a = 10 but after enter number larger then a = 16 it gives wrong answer.
Please help.
As I am not able to post this question if I dont add more info for this question but I assume that the info I provide above is enough to under stand what I want.
Like many of these mathematical puzzles, you are expected to simplify the problem to make it practical. You need to find how many powers of ten in a factorial, not calculate a factorial and then find the number of trailing zeros.
The simplest solution is to count the number of powers of five. The reason you only need to count powers of five is that there is plenty of even numbers in between then to make a 10. For example, 5! has one 0, 10! has 2, 15! has three, 20! has four, and 25! has not five but six as 25 = 5 * 5.
In short you only need calculate the number of powers of five between 1 and N.
// floor(N/5) + floor(N/25) + floor(N/125) + floor(N/625) ...
public static long powersOfTenForFactorial(long n) {
long sum = 0;
while (n >= 5) {
n /= 5;
sum += n;
}
return sum;
}
Note: This will calculate the trailing zeros of Long.MAX_VALUE! in a faction of a second, whereas trying this with BigInteger wouldn't fit, no matter how much memory you had.
Please Note, this is not the mathematical solution as others suggested, this is just a refactoring of what he had initially...
Here I just used BigInteger in place of Int, and simplified your code abit. Your solution is still not optimal. I thought I would just show you what a refactored version of what you posted may look like. Also there was a bug in your initial function. It returned the number of zeros in the whole number instead of just the number of trailing zeros.
import java.math.BigInteger;
import java.util.Scanner;
class factorial {
public static void main(String... ab) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
fact(a);
}
private static void fact(int a) {
BigInteger fact = BigInteger.ONE;
int i, count = 0;
for (i = 1; i <= a; i++) {
fact = fact.multiply(new BigInteger(Integer.toString(i)));
}
String str1 = fact.toString();
for(int j = str1.length() - 1; j > -1; j--) {
if(Character.digit(str1.charAt(j), 10) != 0) {
System.out.println(count);
break;
} else {
count++;
}
}
}
}
Without using factorial
public class TrailingZero {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(trailingZeroes(9247));
}
public static int trailingZeroes(int a) {
int countTwo = 0;
int countFive = 0;
for (int i = a; i > 1; i--) {
int local = i;
while (local > 1) {
if (local % 2 != 0) {
break;
}
local = local / 2;
countTwo++;
}
while (local > 1) {
if (local % 5 != 0) {
break;
} else {
local = local / 5;
countFive++;
}
}
}
return Math.min(countTwo, countFive);
}}

how do i get even placed digits from a number in java

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;
}

sum of digits till the sum is one-digit number

I am a beginner java and trying to solve tricky problem
input=777
output should be 3
7+7+7=21 , 2+1=3;
From the above code if my input is 333 I am getting 9 as answer but when the sum is two digits(777=21) i am getting blank!
public static void main(String[] args)
{
int y=333;//if y is 777 i am getting blank
int sum=0;
String s;
char []ch;
do
{
s=String.valueOf(y);
ch=s.toCharArray();
if(ch.length>1)
{
for(int i=0;i<ch.length;i++)
{
sum+=Character.getNumericValue(ch[i]);
}
}
else
{
System.out.println(sum);
}
y=sum;
}while(ch.length>1);
}
your code maybe loop forever
the right solution is the following below
public static void main(String[] args) throws ParseException {
int y = 777;// if y is 777 i am getting blank
int sum = 0;
String s;
char[] ch;
do {
sum = 0;
s = String.valueOf(y);
ch = s.toCharArray();
if (ch.length > 1) {
for (int i = 0; i < ch.length; i++) {
sum += Character.getNumericValue(ch[i]);
}
} else {
System.out.println(ch[0]);
break;
}
y = sum;
} while (ch.length > 1);
}
Maybe the better choice is the following code
public static void main(String[] args) throws ParseException {
int y = 333;// if y is 777 i am getting blank
int sum = 0;
while (y % 10 != 0) {
sum += y %10;
y = y / 10;
if (0 == y && sum >= 10) {
y = sum;
sum = 0;
}
}
System.out.println(sum);
}
hope that helped
For a task like this, it is best practise to use recursion.
The workflow in pseudocode would look like this:
procedure sumTillOneDigit(n)
split n into it's digits
s := sum of all digits of n
if s has more than one digit:
sumTillOneDigit(s)
else
output s
I am intentionally writing this in pseudocode, since this should help you solving the task. I will not give you a Java implementation, as it looks like a homework to me.
For more information see:
https://en.wikipedia.org/wiki/Recursion_(computer_science)
http://introcs.cs.princeton.edu/java/23recursion/
You are getting that because you put the print statement in else condition..
Also note that to reset your sum value before reusing it. I.e. Set sum=0 at the start of do loop.
EDIT : there are two solutions to print you value
1. Don't put you print statements inside else conditions
Print sum outside the do while loop
First of all you must reset the value of sum variable.
and secondly you must print s in else condition and not the sum and rest is fine.
public static void main(String[] args)
{
int y=333;//if y is 777 i am getting blank
int sum;
String s;
char []ch;
do
{
sum=0;
s=String.valueOf(y);
ch=s.toCharArray();
if(ch.length>1)
{
for(int i=0;i<ch.length;i++)
{
sum+=Character.getNumericValue(ch[i]);
}
}
else
{
System.out.println(s);
}
y=sum;
}while(ch.length>1);
}
I think your solution has wrong basics. There is no point to convert your number to String and handle this as char array. You are doing too much unnecessary operations.
You can do is simpler if you stick with numbers.
You can do it using recursion:
public static int sumRec(int number){
if (number<10){
return number;
}
int sum = 0;
while(number!=0){
sum += number %10;
number /= 10;
}
return sumRec(sum);
}
or itteration
public static int sumIt(int number){
while(number>=10){
int sum = 0;
while(number!=0){
sum += number %10;
number /= 10;
}
number = sum;
}
return number;
}
it is much simpler, right?
You can solve this by 1 line:
public static int sumDigits(int n) {
return (1 + ((n-1) % 9);
}
For example: input 777--> return 1 + ( (777-1) % 9) = 3
Also can work with negative number.
Recursive variant
public static int myFunction(int num){
if(num/10 == 0){
return num;
}
int digitSum = num%10 + myFunction(num/10);
if(digitSum/10 == 0){
return digitSum;
}
return myFunction(digitSum);
}
public static int sum_of_digits(int n) {
return --n % 9 + 1;
}

first java program is not working

I'm new in Java, it's my first attempt to write a program:
I need to write a program that prints the sum of all positive integers smaller
than 1000, that are divided by either 3 or 5.
Here is my (poorly) attempt. after compiling it is just receiving numbers and showing them :
import java.util.Scanner;
public class ex1 {
public static void main(String[] args) {
int num=1;
int count = 1;
while (count <=1000) {
if (count%3==0|count%5==0){
count = count+num;
count++;
}
}
System.out.println(count);
}
}
Given you used a while, I assume you don't know about for loops, so I'll avoid using it.
Your code should:
Your initial sum, before any number, is 0
Iterate (i.e. go through the values) the values from 1 to 1000
If the value is divisible by 3 or 5, add it to a sum.
Print the sum.
Point 1):
int sum = 0;
Point 2):
int value = 1;
while (value <= 1000) {
//do point 3
value++;
}
Point 3):
if ((value%3==0) || (value%5==0)) {
sum = sum + value;
}
Point 4):
System.out.println(sum);
Putting it all together:
int sum = 0;
int value = 1;
while (value <= 1000) {
if ((value%3==0) || (value%5==0)) {
sum = sum + value;
}
value++;
}
System.out.println(sum);
Your main error is in using count both for the sum and for the value check of the while condition. The misusage of the single pipe as or is also a mistake.
Hope this helps
public class Test {
public static void main(String[] args) {
int num=1;
int sum=0;
while (num <=1000) {
if (num%3==0||num%5==0){
sum = sum +num;
}
num++;
}
System.out.println(sum);
}
}
You have put your count++ inside if block. That means if the number is divisible by 3 or 5 then you are incrementing the count . Place it outside of your if block. I have re-write your code as follows -
import java.util.Scanner;
public class ex1 {
public static void main(String[] args) {
int sum = 0;
int count = 1;
while (count <=1000) {
if (count%3==0||count%5==0){
sum = sum + count;
}
count++;
}
System.out.println(sum);
}
}

Project Euler #10 Java solution not working

I'm trying to find the sum of the prime numbers < 2,000,000. This is my solution in Java but I can't seem get the correct answer. Please give some input on what could be wrong and general advice on the code is appreciated.
Printing 'sum' gives: 1308111344, which is incorrect.
Edit:
Thanks for all the help. Changed int to long and < to <= and it worked flawlessly, except for being an inefficient way of finding prime numbers :)
/*
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
*/
class Helper{
public void run(){
Integer sum = 0;
for(int i = 2; i < 2000000; i++){
if(isPrime(i))
sum += i;
}
System.out.println(sum);
}
private boolean isPrime(int nr){
if(nr == 2)
return true;
else if(nr == 1)
return false;
if(nr % 2 == 0)
return false;
for(int i = 3; i < Math.sqrt(nr); i += 2){
if(nr % i == 0)
return false;
}
return true;
}
}
class Problem{
public static void main(String[] args){
Helper p = new Helper();
p.run();
}
}
The result will be too large to fit into an integer, so you are getting an overflow. Try using a BigInteger or a long instead. In this case a long is enough.
You're treating as prime those numbers that are only divisible by their square root (like 25). Instead of i < Math.sqrt(nr) try i <= Math.sqrt(nr).
That's a really inefficient way to find primes, incidentally.
Your isPrime doesn't work for squares. isPrime(9) returns true.
As already stated errors were two:
you used an int that is not big enough to hold that sum.. you should have used a long
you used < instead that <=, and it was a wrong guard for the cycle
Apart from that what you are doing is really inefficient, without going too deep inside this class of algorithms (like Miller-Rabin test) I would suggest you to take a look to the Sieve of Eratosthenes.. a really old approach that teaches how to treat a complex problem in a simple manner to improve elegance and efficiency with a trade-off of memory.
It's really cleaver: it keeps track of a boolean value for every prime up to your 2 millions that asserts if that number is prime or not. Then starting from the first prime it excludes all the successive numbers that are obtained by multiplying the prime it is analyzing for another number. Of couse more it goes and less numbers it will have to check (since it already excluded them)
Code is fair simple (just wrote it on the fly, didn't check it):
boolean[] numbers = new boolean[2000000];
long sum = 0;
for (int i = 0; i < numbers.length; ++i)
numbers[i] = true;
for (int i = 2; i < numbers.length; ++i)
if (!numbers[i])
continue;
else {
int j = i + i;
while (j < 2000000) {
numbers[j] = false;
j += i;
}
}
for (int i = 2; i < 2000000; ++i)
sum += numbers[i] ? i : 0;
System.out.println(sum);
Of course this approach is still unsuitable for high numbers (because it has to find all the previous primes anyway and because of memory) but it's a good example for starters to think about problems..
by using Sieve of Eratosthenes effectively, i solved the problem, here is my code
public class SumOfPrime {
static void findSum()
{
long i=3;
long sum=0;
int count=0;
boolean[] array = new boolean[2000000];
for(long j=0;j<array.length;j++)
{
if((j&1)==0)
array[(int)j]=false;
else
array[(int)j]=true;
}
array[1]=false;
array[2]=true;
for(;i<2000000;i+=2)
{
if(array[(int)i] & isPrime(i))
{
array[(int)i]=true;
//Sieve of Eratosthenes
for(long j=i+i;j<array.length;j+=i)
array[(int)j]=false;
}
}
for(int j=0;j<array.length;j++)
{
if(array[j])
{
//System.out.println(j);
count++;
sum+=j;
}
}
System.out.println("Sum="+sum +" Count="+count);
}
public static boolean isPrime(long num)
{
boolean flag=false;
long i=3;
long limit=(long)Math.sqrt(num);
for(;i<limit && !(flag);i+=2)
{
if(num%i==0)
{
flag=false;
break;
}
}
if(i>=limit)
flag=true;
return flag;
}
public static void main(String args[])
{
long start=System.currentTimeMillis();
findSum();
long end=System.currentTimeMillis();
System.out.println("Time for execution="+(end-start)+"ms");
}
}
and the output is
Sum=142913828922 Count=148933
Time for execution=2360ms
if you have doubt, please do tell
Here is my solution
public class ProjectEuler {
public static boolean isPrime(int i) {
if (i < 2) {
return false;
} else if (i % 2 == 0 && i != 2) {
return false;
} else {
for (int j = 3; j <= Math.sqrt(i); j = j + 2) {
if (i % j == 0) {
return false;
}
}
return true;
}
}
public static long sumOfAllPrime(int number){
long sum = 2;
for (int i = 3; i <= number; i += 2) {
if (isPrime(i)) {
sum += i;
}
}
return sum;
}
/**
* #param args
*/
public static void main(String[] args) {
System.out.println(sumOfAllPrime(2000000));
}
}

Categories