Recursion - Finding the Amount of Even Digits in a Number - java

I'm having trouble with this problem. I am supposed to find the amount of even digits in a number.
So for example, if the number is 146, then there are 2 even digits.
And if the number is 802, then there are 3 even digits.
I was told that n % 10 is the value of the rightmost digit. n / 10 contains all of the digits except the rightmost digit.
public static int countEvenDigits(int n) {
int rightDigit = n % 10;
int count= 0;
if (rightDigit / 10 == 0) {
count++;
}
return countEvenDigits(count);
}

With recursion, you can do it like this
int calcRec(int num) {
if (num / 10 == 0) {
return num % 2 == 0 ? 1 : 0;
}else{
return (num % 10 % 2 == 0? 1:0)+calcRec(num/10);
}
}
But its not suitable case for using recursion.

Another answer:
public static int countEvenDigits(int number) {
if (number == 0) return 0;
int lastDigit = number % 10;
int firstDigits = number / 10;
if (lastDigit % 2 == 0) {
return 1 + countEvenDigits(firstDigits);
} else {
return 0 + countEvenDigits(firstDigits);
}
}
Recursion always needs one or more "base case"s, where recursion stops (in this case, no digits left); and one or more "recursive cases" where you continue to work with a smaller problem (with the firstDigits).
I agree with #kimreik that this is not a good use of recursion (as the problem could be better solved with a while-loop); but it is a very typical example when starting to learn to program recursion, as I suspect the OP is doing.

Ok so the idea of using recursion to process a series is that you define a function that process and removes one element from the set. Seeing as you are interested in digits you have 2 options to define your set from a given int.
The first option is to cast the int to a string and cast each character back into an int. Which is what I implemented below
Alternatively you could do division by your base (10) to the power of the significance of the digit (0 being the right most digit and counting left.) Or more eloquently as kimreik reducing the number by integer division sequentially. (142 / 10 / 10 == 142 / 100 == 1 == "142"[0])...
The syntax for converting your integer to a string is Integer.toString(int). This will be useful as it allows us to access each digit without doing any math and also allows us to take sub-strings which we can pass to the next instance of our recursive method.
Now that we have our array to process we need to address the fundamentals of recursion. Recursion has three parts. These parts are as follows, some starting state or initial values, a base case and a recursive step.
For this problem we must set our initial values for the count of even digits and we will be given a string to process. We will start our count at 0 but it will be a variable passed to each call to our method.
Our base case is the empty sting, that is a blank number. Which contains 0 even numbers. Because we are recurring towards an empty set this type of algorithm is called reductive.
Now our recursive step is where everything really happens. It must read a digit from our string and then remove it from the string by passing the remaining digits to the next instance of the function.
Now that we know what we need to do what does out function look like?
public class HelloWorld{
public static int recursiveGetEvenDigits(String arg){
int count = 0;
if(arg.length()<1){
return(0); // base case
}
else{
count = Character.getNumericValue(arg.charAt(0))%2 == 0 ? 1 : 0; //If else shorthand
return(count+recursiveGetEvenDigits(arg.substring(1)));
}
}
public static int getEvenDigits(int n){ // provide user arguments
return(recursiveGetEvenDigits(Integer.toString(n))); // set initial conditions
}
public static void main(String []args){
System.out.println(getEvenDigits(142));
}
}
Just to be funny the whole if else logic could be reduced to one line again with the same shorthand I used above.
public class HelloWorld{
public static int recursiveGetEvenDigits(String arg){
return arg.length() < 1 ? 0 : (Character.getNumericValue(arg.charAt(0)) % 2 == 0 ? 1 : 0)+recursiveGetEvenDigits(arg.substring(1));
}
public static int getEvenDigits(int n){ // provide user arguments
return(recursiveGetEvenDigits(Integer.toString(n))); // set initial conditions
}
public static void main(String []args){
System.out.println(getEvenDigits(142));
}
}
prints 2

here is a quick pseudo code
function sumEven(int num){
if(num==0)
return 0;
int var =num%10;
if(var % 2)
return var+(num/10)
else
return 0+(num/10)
}

Related

I have to convert octal basis to Decimal but in String format

I wrote a program which, at first, was giving correct answers however I later wrote another method which caused my program to start failing. After that I deleted the second method but nothing seems to work to fix it. Can you guys tell me what the problem is?
Note: Method isNumeric just checks if the input String contains a non-numeric character.
For example: a number in octal basis "115" needs to be converted to decimal, meaning
(115)8 -> (?)10
The following formula gives us this:
115 = (1 × 8²) + (1 × 8¹) + (5 × 8⁰) = 77
This is the formula that the code is supposed to follow.
Therefore the result of the conversion of 115 in octal basis to decimal is 77.
Another limitation of this is that this must use recursion.
It worked in the sense that it gave the correct result 5 times in a row for different String number inputs but something along the way changed and now gives wrong results.
public static int octalStringToDecimal(String numString) {
//Base case the numeric value is just 0 or where String is empty
if ((numString.equals(""))) {
return -9999;
}
//the String does not contain numeric characters
if((!isNumeric(numString))){
return -9999;
}
int rem, sum = 0, i = 0, basis = 8;
int number = Integer.parseInt(numString); //this is n
//while our number is not 0 then we keep on parsing
while (number != 0) {
rem = number % 10;
number = number / 10;
sum = rem * ((int) Math.pow(basis, i)) + octalStringToDecimal(String.valueOf(number));
i++;
}
//when out number is equal to 0 then we return the value
return sum;
}
public static boolean isNumeric(String string) {
try {
Integer.parseInt(string);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Your "recursive" method contains a while loop. Recursive methods do not usually contain loops. A recursive method must contain a condition that terminates the recursion. If that condition is not true, then the method changes the arguments it was called with and then calls itself.
Since the parameter to your recursive method is a string, it seemed logical to me to extract the digits of the number using method substring(int, int).
Since the input number is supposed to be an octal number, apart from checking whether it contains only digits, you also need to check whether it is a valid octal number. In other words each digit in the number must be between 0 (zero) and 7 (seven).
In the below code, I initially take the rightmost digit of the input number and multiply it by 80. Then, in every recursive call, I take the digit immediately to the left of the last digit I converted and increase the exponent by one. Hence, the first recursive call will take the digit to the left of the rightmost digit and multiply it by 81.
Once I have converted the leftmost digit, the recursion stops.
public class Converter {
private static final int BASE = 8;
private static void checkDigit(String digit) {
int numeral = Integer.parseInt(digit);
if (numeral > 7) {
throw new IllegalArgumentException("Not a valid octal digit: " + digit);
}
}
private static int convertDigit(String digit, int exponent) {
return (int) Math.pow(BASE, exponent) * Integer.parseInt(digit);
}
private static int octalStringToDecimal(String numString, int exponent, int start) {
if (start >= 0) {
String digit = numString.substring(start, start + 1);
checkDigit(digit);
return convertDigit(digit, exponent) + octalStringToDecimal(numString, exponent + 1, start - 1);
}
else {
return 0;
}
}
public static void main(String[] args) {
String numString = "115";
System.out.println(octalStringToDecimal(numString, 0, numString.length() - 1));
}
}

How to find the 5th perfect number (which is 33550336)? The problem is taking forever to run

I am trying to write a Java method that checks whether a number is a perfect number or not.
A perfect number is a number that is equal to the sum of all its divisor (excluding itself).
For example, 6 is a perfect number because 1+2+3=6. Then, I have to write a Java program to use the method to display the first 5 perfect numbers.
I have no problem with this EXCEPT that it is taking forever to get the 5th perfect number which is 33550336.
I am aware that this is because of the for loop in my isPerfectNumber() method. However, I am very new to coding and I do not know how to come up with a better code.
public class Labreport2q1 {
public static void main(String[] args) {
//Display the 5 first perfect numbers
int counter = 0,
i = 0;
while (counter != 5) {
i++;
isPerfectNumber(i);
if (isPerfectNumber(i)) {
counter++;
System.out.println(i + " ");
}
}
}
public static boolean isPerfectNumber(int a) {
int divisor = 0;
int sum = 0;
for (int i = 1; i < a; i++) {
if (a % i == 0) {
divisor = i;
sum += divisor;
}
}
return sum == a;
}
}
This is the output that is missing the 5th perfect number
Let's check the properties of a perfect number. This Math Overflow question tells us two very interesting things:
A perfect number is never a perfect square.
A perfect number is of the form (2k-1)×(2k-1).
The 2nd point is very interesting because it reduces our search field to barely nothing. An int in Java is 32 bits. And here we see a direct correlation between powers and bit positions. Thanks to this, instead of making millions and millions of calls to isPerfectNumber, we will be making less than 32 to find the 5th perfect number.
So we can already change the search field, that's your main loop.
int count = 0;
for (int k = 1; count < 5; k++) {
// Compute candidates based on the formula.
int candidate = (1L << (k - 1)) * ((1L << k) - 1);
// Only test candidates, not all the numbers.
if (isPerfectNumber(candidate)) {
count++;
System.out.println(candidate);
}
}
This here is our big win. No other optimization will beat this: why test for 33 million numbers, when you can test less than 100?
But even though we have a tremendous improvement, your application as a whole can still be improved, namely your method isPerfectNumber(int).
Currently, you are still testing way too many numbers. A perfect number is the sum of all proper divisors. So if d divides n, n/d also divides n. And you can add both divisors at once. But the beauty is that you can stop at sqrt(n), because sqrt(n)*sqrt(n) = n, mathematically speaking. So instead of testing n divisors, you will only test sqrt(n) divisors.
Also, this means that you have to start thinking about corner cases. The corner cases are 1 and sqrt(n):
1 is a corner case because you if you divide n by 1, you get n but you don't add n to check if n is a perfect number. You only add 1. So we'll probably start our sum with 1 just to avoid too many ifs.
sqrt(n) is a corner case because we'd have to check whether sqrt(n) is an integer or not and it's tedious. BUT the Math Overflow question I referenced says that no perfect number is a perfect square, so that eases our loop condition.
Then, if at some point sum becomes greater than n, we can stop. The sum of proper divisors being greater than n indicates that n is abundant, and therefore not perfect. It's a small improvement, but a lot of candidates are actually abundant. So you'll probably save a few cycles if you keep it.
Finally, we have to take care of a slight issue: the number 1 as candidate. 1 is the first candidate, and will pass all our tests, so we have to make a special case for it. We'll add that test at the start of the method.
We can now write the method as follow:
static boolean isPerfectNumber(int n) {
// 1 would pass the rest because it has everything of a perfect number
// except that its only divisor is itself, and we need at least 2 divisors.
if (n < 2) return false;
// divisor 1 is such a corner case that it's very easy to handle:
// just start the sum with it already.
int sum = 1;
// We can stop the divisors at sqrt(n), but this is floored.
int sqrt = (int)Math.sqrt(n);
// A perfect number is never a square.
// It's useful to make this test here if we take the function
// without the context of the sparse candidates, because we
// might get some weird results if this method is simply
// copy-pasted and tested on all numbers.
// This condition can be removed in the final program because we
// know that no numbers of the form indicated above is a square.
if (sqrt * sqrt == n) {
return false;
}
// Since sqrt is floored, some values can still be interesting.
// For instance if you take n = 6, floor(sqrt(n)) = 2, and
// 2 is a proper divisor of 6, so we must keep it, we do it by
// using the <= operator.
// Also, sqrt * sqrt != n, so we can safely loop to sqrt
for (int div = 2; div <= sqrt; div++) {
if (n % div == 0) {
// Add both the divisor and n / divisor.
sum += div + n / div;
// Early fail if the number is abundant.
if (sum > n) return false;
}
}
return n == sum;
}
These are such optimizations that you can even find the 7th perfect number under a second, on the condition that you adapt the code for longs instead of ints. And you could still find the 8th within 30 seconds.
So here's that program (test it online). I removed the comments as the explanations are here above.
public class Main {
public static void main(String[] args) {
int count = 0;
for (int k = 1; count < 8; k++) {
long candidate = (1L << (k - 1)) * ((1L << k) - 1);
if (isPerfectNumber(candidate)) {
count++;
System.out.println(candidate);
}
}
}
static boolean isPerfectNumber(long n) {
if (n < 2) return false;
long sum = 1;
long sqrt = (long)Math.sqrt(n);
for (long div = 2; div <= sqrt; div++) {
if (n % div == 0) {
sum += div + n / div;
if (sum > n) return false;
}
}
return n == sum;
}
}
The result of the above program is the list of the first 8 perfect numbers:
6
28
496
8128
33550336
8589869056
137438691328
2305843008139952128
You can find further optimization, notably in the search if you check whether 2k-1 is prime or not as Eran says in their answer, but given that we have less than 100 candidates for longs, I don't find it useful to potentially gain a few milliseconds because computing primes can also be expensive in this program. If you want to check for bigger perfect primes, it makes sense, but here? No: it adds complexity and I tried to keep these optimization rather simple and straight to the point.
There are some heuristics to break early from the loops, but finding the 5th perfect number still took me several minutes (I tried similar heuristics to those suggested in the other answers).
However, you can rely on Euler's proof that all even perfect numbers (and it is still unknown if there are any odd perfect numbers) are of the form:
2i-1(2i-1)
where both i and 2i-1 must be prime.
Therefore, you can write the following loop to find the first 5 perfect numbers very quickly:
int counter = 0,
i = 0;
while (counter != 5) {
i++;
if (isPrime (i)) {
if (isPrime ((int) (Math.pow (2, i) - 1))) {
System.out.println ((int) (Math.pow (2, i -1) * (Math.pow (2, i) - 1)));
counter++;
}
}
}
Output:
6
28
496
8128
33550336
You can read more about it here.
If you switch from int to long, you can use this loop to find the first 7 perfect numbers very quickly:
6
28
496
8128
33550336
8589869056
137438691328
The isPrime method I'm using is:
public static boolean isPrime (int a)
{
if (a == 1)
return false;
else if (a < 3)
return true;
else {
for (int i = 2; i * i <= a; i++) {
if (a % i == 0)
return false;
}
}
return true;
}

mutually recursive functions

I am trying to understand why the below functions are outputting zero for any input I give them. I would have thought that based on the recursive nature that inputting a 2 to function g, would produce 12. Any integer I seem to use for either function simply outputs 0. Can anyone point to where I am going wrong in my thought process?
public class dsdsfsd {
public static int i(int n) {
if (n == 0) return 0;
return i(n-1) + g(n-1);
}
public static int g(int n) {
if (n == 0) return 0;
return g(n-1) + i(n);
}
public static void main(String[] args) {
int a = 2;
System.out.println(g(a));
System.out.println(i(a));
System.out.println(g(g(a)));
}
}
Sure. The only value these functions can return is 0. That's the base case, and the higher cases do nothing but add up those zeroes. Where do you see another value entering the equation?
If either function has zero as an argument, it returns 0.
If it has any other value, it returns the sum of two recursive calls.
The sum of two zeros is zero.
Where exactly do you expect the function to produce anything but zero?
Your problem is not on the recurrence but on the initialization of your variables.
I reckon that you try to calculate some linked coefficients by the formulas:
g(n) = g(n-1) + i(n)
i(n) = i(n-1) + g(n-1)
g(0) = 0
i(0) = 0
However, as you initialized g and i to 0, i(1) = g(0) + i(0) = 0 + 0 = 0, and any values of g(n) or i(n) will be 0 for the same reason which is: you keep adding 0's and 0's.
Instead if you want to have a non-null result you should change at least one of your initialization, for example:
g(0) = 1
i(0) = 1
That way, you have i(1) = g(0) + i(0) = 1 + 1 = 2 and g(1) = g(0) + i(1) = 1 + 2 = 3.
This is more a mathematical issue in the end.
You could reduce this to a single function for simplicity, since the mutual recursion is irrelevant:
public static int func(int n) {
if (n == 0) return 0;
return func(n-1);
}
Notice there are only 2 ways for this to return:
It can return 0 directly in the base case
It can return the result of recursing.
Think about that. At some point, it must stop recursing (or else it will run forever). What happens when the base case of 0 is returned? Your function turns into something like this (for imagining purposes only of course):
public static int func(int n) {
if (n == 0) return 0;
return 0;
}
Therefore, 0 is the only value your function(s) are capable of returning, since it's the only concrete value ever returned.

How to print all palindromes upto 1000 without using any String,StringBuilder?

I have to write a code for printing all palindrome numbers up to 1000. Here is my code. I have dealt with 3 scenarios:
1-digit number
2-digit number
3-digit number
My third scenario is not printing just the palindromes but prints all the numbers. A hint will help me solve this.
public class PrintPalindrome {
public static void main(String args[])
{
Integer[] array=new Integer[1000];
for(int i=0;i<array.length;i++)
{
array[i]=i+1;
printPalindrome(array[i]);
//System.out.println(array[i]);
}
}
public static void printPalindrome(Integer a)
{
String num=Integer.toString(a);
int length=num.length()-1;
//System.out.println(num);
if(num.length()<=1)
{
System.out.println("" + num);
}
else if(num.length()==2)
{
if(num.charAt(0)==num.charAt(1))
System.out.println(num);
}
else if(num.length()>2)
{
//now deal with the numbers whose length is greater than 2
for(int i=0;i<=length;i++)
{
if(num.charAt(i)==num.charAt(length-i))
System.out.println(num);
}
}
}
}
Work out a solution with arithmetic…
This doesn't necessarily help with the code that you've already got, but it's approach to the problem in the title, How to print all palindromes upto 1000, which may be helpful to others who come across this question. It's often fun to try to solve these problems using the properties of the numbers, without worrying about converting them to strings. In this case, note that for any number n, you can get the leading digit by n % 10, that is, the remainder of n divided by 10, or n modulo 10. You can get the number whose digits are the same as the remaining digits of n as the integer quotient of n/10. E.g.,
1234 % 10 = 4
1234 / 10 = 123
Now, if you keep applying this deconstruction, you can get the individuals digits:
123 % 10 = 3
123 / 10 = 12
12 % 10 = 2
12 / 10 = 1
1 % 10 = 1
1 / 10 = 0
Now, if you take those numbers in the same order that you got them (4, 3, 2, 1), you can reconstruct the "reverse" number:
1 + 10(2 + 10(3 + 10(4 + 0))) = 4321
If we call this the reverse of a number, then number is a palindrome if and only if it's equal to it's reverse.
…and then translate it to Java
This is fairly straightforward to implement in Java, and it doesn't require any special casing about 1-digit numbers, 2-digit numbers, etc., or string manipulation. (As Kent points out in the comments, there's still a limit on how large the numbers that this handles is, but if you need to handle big numbers, you could (i) switch to a long; (ii) switch to a BigInteger.)
public class PalindromeExample {
/**
* Returns the number whose digits (base 10) are the reverse
* of number's (with no leading zeros).
* #param number the number to reverse
* #return the reversed number
*/
public static int reverse( int number ) {
int result = 0;
while ( number > 0 ) {
result = result * 10 + (number % 10);
number = number / 10;
}
return result;
}
/**
* Show the numbers less than 10000 whose digit sequences
* are palindromes.
*/
public static void main(String[] args) {
for ( int i = 0; i < 10000; i++ ) {
if ( i == reverse( i ) ) {
System.out.println( i );
}
}
}
}
0
1
2
3
…
9
11
22
…
99
101
111
…
151
161
…
8008
8118
…
9339
9449
9559
9669
9779
9889
9999
if(num.charAt(i)==num.charAt(length)-i)
is wrong. Even if you set parenthesis in the "right" place you still be wrong, because for example:
charAt(0) == charAt(3) //and what's char at 3?
if(num.charAt(i)==num.charAt(length-i-1))
should do the trick but then placing it in a for loop doesnt make any sense.
When a 3-digit number has 1st and 3rd digit the same it is actually a palindrome. Every other loop will just mess up your output.
For the requirement, we don't have to convert to string.
pls try if this works for you: (could be an one-liner)
for (int i = 1; i < 1000; i++)
if (i<10 ||(i<100&&i%11==0)||(i>100&&i%10==i/100) )
System.out.println(i);
Handling scenarios for each digit length to check if a number is a palindrome is not an appropriate approach.
Trying what the other answers suggest - like going through each and every number and checking if it is palindrome by reversing number digit by digit is better but even then it is not very efficient as it is brute force.
So, I would like to some suggestions if I may:-
Rather than going for brute force, any other approach if possible is preferable.
Even while resorting to brute force, using the library functions is
better and at least as efficient as any code we can write. ex - Integer.reverse() function for reversing an integer.
I have had a try at generating the palindromes(rather than trying one by one). This is not bug-proof yet as I have not tested extensively but should be able to convey the concept.
public class PrintPalin {
public static void main(String[] args) {
// TODO Auto-generated method stub
//The first palindrome = 1
int i = 1;
while(i<=10000){
System.out.println(i);
i = nextPalin(i);
}
}
static int nextPalin(int i){
StringBuilder sb = new StringBuilder(String.valueOf(i));
int len = sb.length(), right = len/2, left;
if(len%2!=0 || len == 1){
left = right;
}else{
left = right-1;
}
//System.out.println(left + " " + right);
while(right<len && sb.charAt(right)=='9'){
sb.setCharAt(right, '0');
right++;
sb.setCharAt(left, '0');
left--;
}
if(right==len){
sb.insert(0, '1');
//sb.append("1");
sb.setCharAt(right, '1');
}else{
sb.setCharAt(right, (char)(sb.charAt(right)+1));
if(right != left){
sb.setCharAt(left, (char)(sb.charAt(left)+1));
}
}
i = Integer.valueOf(new String(sb));
return i;
}
}
Where the above approach wins is when the density of palindromes per number tried is less when we go for higher numbers but for the range that is asked(0 to 1000) it would not be able to make much difference.
I am open to other approaches. I was thinking may be decoding the addition required to generate the next palindrome number should be faster and better approach instead of using strings the basic idea of both approaches are similar so should not be much difficult(though I am not sure).
I believe you want to check whether the number is a palindrome or not before you print it. You just need to seprate checking and printing like this:
if(num.length()>2)
{
boolean isPalindrome=true;
for(int i=0;i<=length/2;i++) //you compare one half, to the other
{
if(num.charAt(i)!=num.charAt(length-i))
isPalindrome=false;
}
if(isPalindrome)
System.out.println(num);
}
This should work for a number of any length.

Nested "FOR-loops" not working

I am doing an excercise in the book "Java how to program". The excercise wants me to write a method that determines if a number is "prime". (A "Prime number" is a positiv integer which is only dividable with itself and 1). Then I am supposed to implement the method in an application that displays all integers up to 10 000.
I use "double-values" to test whether the remainder is 0 or not, to test dividability.
Anyway, I just don´t get the program to work, it displays all numbers fro 3, with an increement on how many times each number is displayed (3 44 555 etc). Can anyone please tell me what I´m doing wrong?
The code is the following:
public class Oppgave625
{
public static void main(String[] args)
{
for(double a = 2; a <= 10000; a++)
{
for(double b = 1; b < a; b++)
{
if (prime(a, b) !=0)
{
System.out.printf("%.0f ", prime(a, b));
}
}
}
}
static double prime(double x, double y)
{
if (x % y != 0)
{
return x;
}
else
{
return 0;
}
}
}
Use int instead. double is not good for this purpose
you might want to read this article to understand the use of the % Operator for floating point numbers.
Actually, there were many individual errors in here. I shortened the prime() function to the point where it was only a modulo op, so I was able to inline it. Second, I inverted the test so it checked for numbers that do not have a remainder, and continues to the next number as soon as it finds a divisor. Third, I changed b = 1 so that we do not check for numbers divisible by 1, because this would result to all numbers. Finally, I only print out the numbers for which we do not discover a divisor. The final result:
public static void main(String[] args) {
outer:
for (int a = 2; a <= 1000; a++) {
for (int b = 2; b < a; b++) {
if (a % b == 0) {
continue outer;
}
}
System.out.println(a);
}
}
Edit: I forgot to mention, I also changed the types from floats to ints, since I'm sure that's what you meant.
It's great that you posted sample code for this, but there are several things that are wrong:
you should not use a floating point type for this, but an int or a long. Floating point types should never be used for precise values.
you are making two calls to your prime function, effectively doubling the required steps
your prime function only tells you whether two numbers divide themselves evenly, it does not tell you whether one is a prime or not
for prime numbers, you should use a more efficient algorithm instead of calculating the same values over and over for each number. Look up Sieve of Eratosthenes.
You are approaching the problem like this: The number A is NOT prime, whenever i can find a number B that can divide A without a remainder.
Bur right now, you print out A whenever it is not dividable by B.
Instead you could say: whenever A not divisible by B, increase B. When i found a B to divide A, quit the inner loop, print nothing.
When i found no B, print A and quit loop.
Furthermore, you only have to test for divisibility of A until (a/2)-1.
A prime number is a number that is only divisible by one and itself. That is: one number. Your code is comparing two numbers as in the Euclidean algorithm for testing coprime-ness. This is very different than testing if a number is prime.
Your code should look something like this:
for i = 2 to 10,000 {
if( isPrime(i) ){
print i
}
}
function isPrime( int n ){
for i = 2 to n {
next if i == n
if( n % i == 0 ){
return 0;
}
}
return 1;
}
boolean isPrime = true;
for (int i = 2; i<=100; i++){
for(int j = 2; j<=i/2; j++){
isPrime = true;
if (i%j==0){
isPrime = false;
break;
}
}
if (isPrime){
Log.d("PrimeNumber",""+i);
}
}

Categories