Cannot find symbol compile error in for loop - java

I'm having a problem with my code here. I'm trying to find all multiples of 3 and 5 up to one thousand and add them all up, and at the end when I try to output the sum, java gives me a 'cannot find symbol' error. Can anybody figure out what's wrong here?
public class Problem1
{
public static void main(String []args)
{
//int sum1;
//int sum2;
int finalSum;
for(int i = 0; i < 1000; i++)
{
if(i % 3 == 0)
{
int sum;
sum += i;
}
else if(i % 5 == 0)
{
int sum;
sum += i;
}
}
System.out.println(sum);
}
}

Java has block scoping, which means that the sum declared in between {}s (braces) is not visible outside. Declare sum once, outside of the for loop.
public class Problem1
{
public static void main(String []args)
{
int sum = 0;
for(int i = 0; i < 1000; i++)
{
if(i % 3 == 0)
{
sum += i;
}
else if(i % 5 == 0)
{
sum += i;
}
}
System.out.println(sum);
}
}

you can not declare sum in loop.Then it is local to that method.

It's because you're "creating" sum inside the if statements which limits their scope - they're created within the if blocks and destroyed at the next closing brace.
Get rid of those two int sum; lines inside the if blocks and put it at the top of the function (where the rather useless finalSum is). Or just use finalSum everywhere.
You can also combine the if conditions for shorter code:
public class Problem1
{
public static void main(String []args)
{
int finalSum = 0;
for(int i = 0; i < 1000; i++)
if((i % 3 == 0) || (i % 5 == 0))
finalSum += i;
System.out.println(finalSum);
}
}

you have defined the variable sum inside the the if/else which limits the scope of the variable.System.out.print() statement is outside the scope of sum hence you are getting the error.
public class Problem1
{
public static void main(String []args)
{
int sum=0;
for(int i = 0; i < 1000; i++)
{
if(i % 3 == 0)
{
sum += i;
}
else if(i % 5 == 0)
{
sum += i;
}
}
System.out.println(sum);
}
}

Related

Find largest prime factor for the number 600851475143L [duplicate]

This question already has answers here:
Algorithm to find Largest prime factor of a number
(30 answers)
Closed 4 years ago.
I am getting output for 13195L, 24L, and 23L. But I am not getting output for 600851475143L. The system is going into infinite loop. Please help me identify what is wrong with my code.
package problem3;
public class problem3_version1 {
public static void main(String[] args) {
long dividend = 600851475143L;
// long dividend=13195L;
// long dividend=24L;
// long dividend=23L;
int num_of_divisors = 0;
for (long i = dividend - 1; i >= 2; i--) {
System.out.println("i =" + i);
int count = 2;
for (long j = 2; j < i; j++) {
if (i % j == 0)
count++;
if (count == 3)
break;
}
if (count == 2) {
if (dividend % i == 0) {
num_of_divisors++;
System.out.println("Highest factor is " + i);
break;
}
}
}
if (num_of_divisors == 0)
System.out.println("The number is prime");
}
}
try this solution :
public class LargestPrimeFactor
{
public static int largestPrimeFactor(long number) {
int i;
for (i = 2; i <= number; i++) {
if (number % i == 0) {
number /= i;
i--;
}
}
return i;
}
public static void main(String[] args) {
System.out.println(LargestPrimeFactor.largestPrimeFactor(600851475143l));
}
}
The problem was because you have nested loop with very big number, and that what made the loop

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

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.

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