Translate Pseudocode and get the result - java

Can you help translating this Pseudocode into java and get the result
as I tried but didn't get the results and I'm starting to learn Java.
num=2
create list called list
while(true){
empty list
bool = false
for i=1 to num-1
if(num mod i==0){
add i to list
if((i &(bitwise)1)==1)
bool=!bool
}
if sum(list)==num && bool//logical and
return num; //Found the number we seek
num++
}
This is Java translating but I'm not sure as it didn't get the result numbers
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.ArrayList;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
//set a number
int num=2;
//make list called list
ArrayList<Integer> list = new ArrayList<Integer>();
//run this while true, but just saying true makes an infinite loop
boolean bool = true;
while(bool){
//clear the list
list.clear();
//set
bool = false;
for (int i= 1; i < num-1; i = i + 1){
//If number modulo i is 0
if((num % i) ==0){
list.add(i);
//If bitwise and of i and 1 is true
//This is doing things with the underlying binary
if((i & 1)==1)
//Reverse the valuse of bool
bool = !bool;
}
int sum = 0;
//for each element in the list
for(int x: list){
//add it to sum
sum += sum;
}
//execute is sum and num are the same and bool is true
if ((sum == num )&& bool){}
return num;
//This does nothing as it is never reached. return ends your execution
num++;
}
}
}
}

This sure looks like some assignment. Anyways, here's the translation of the pseudocode:
public int code ()
{
int num = 2;
List<Integer> list = new ArrayList<> ();
while (true)
{
list.clear ();
boolean bool = false;
for (int i = 1; i < num; ++i)
{
if (num % i == 0)
{
list.add (i);
if ((i & 1) == 1)
{
bool = !bool;
}
}
}
if (sum (list) == num && bool)
{
return num;
}
num++;
}
}
private int sum (List<Integer> list)
{
return list.stream ().mapToInt (i -> i).sum ();
}
The code is sure taking time to print out any result.
Try calling the code method and you'll see.
Apart from that, what number this code is trying to find, you may ask?
Well, through logical deduction, I can tell that this code is trying to find the smallest Perfect Number that has odd number of odd factors. Try thinking about it.

It will never get the result, most probably at least.
As someone already said it is trying to find "the smallest Perfect Number that has odd number of odd factors", and any number that have in its sum odd number of odd numbers is odd. So its searching for odd perfect number which is yet to proven if it exist or not that is why it will never give you result fast enough. It could take million years it could take forever. The question was supposed to be solved by logic.
BTW: Actually I am the one who made this pseudocode, better luck solving the code next weak. (:

Related

Find primefactors Java

I am new to JAVA programming and I am having hard time doing this lab
import java.util.*;
public class FindPrimes
{
private static ArrayList<Integer> myList = new ArrayList();
//post: returns true if value is a prime number
public static boolean isPrime(int value)
{
if(value < 2 || value % 2 == 0)
return false;
if(value == 2)
return true;
for (int i = 3; i * i <= value; i += 2)
if (value % i == 0)
return false;
return true;
//temporary return so program compiles
}
//post: returns the index of the first non-prime number in myList.
// returns -1 if all numbers are prime
private static int findNotPrime()
{
for(int i=0; i<myList.size(); i++){
if(!isPrime(myList.get(i)))
return i;
}
/*ex: [60] will return 0
[2,30] will return 1
[2,2,15] returns 2
[2,2,3,5] returns -1
*/
return -1; //temporary return so program compiles
}
//post: returns the smallest factor of a number
private static int findSmallestFactor(int num)
{
for (int i = 2; i*i<= num; i++) {
if (num % i == 0)
return i;
}
/* ex:findSmallestFactor(8) -> 2
findSmallestFactor(9) -> 3
findSmallestFactor(7) -> 7
*/
return -1; //temporary return so program compiles
}
//post: recursive method that places the prime factorization into myList
//
private static void generateList()
{
//generateList();
int var = findNotPrime();
if(var != -1){
int n = findSmallestFactor(myList.get(var));
myList.set(var, n);
myList.add(myList.get(var)/n);
generateList();
}
}
/* Hint: Check the list to find the first non-prime factor.
If all the numbers are prime, you are done.
Otherwise, * find the smallest factor of the first non-prime and its cofactor.
* replace the first non-prime with its smallest factor and add the cofactor to the end
* repeat the whole process */
//post: calcualtes the prime factorization of number and returns the list containing factors
public static ArrayList<Integer> calculateFactors(int number)
{
/* place number in myList, generate the prime factorizations and return the list.*/
myList.add(new Integer(number));
//System.out.println(myList);
generateList();
return myList;
}
public static void main(String[] arg)
{
System.out.println(8 + ":" + calculateFactors(8));
myList.clear();
System.out.println(60 + ":" + calculateFactors(60));
myList.clear();
System.out.println(75 + ":" + calculateFactors(75));
}
}
The error code I get is
"Exception in thread "main" java.lang.StackOverflowError"
I have tested all the methods and they all seem to be working. I don't know why this happens.
You call generateList inside itself, causing an infinite recursion thus your stack overflows.
Don't know if you have figured out your task yet. But I did this task since it seemed like fun and since I've never done it before and.
What is the rules for answering a thread the asking person has solved already? Well.. it's easier to get forgiveness than permission...
The problem is mainly in generateList where you don't "save" a temp variable. This can be solved like this:
if(var != -1){
int temp=myList.get(var);
int n = findSmallestFactor(temp);
myList.set(var, n);
myList.add(temp/n);
generateList();
}
Other than that you have to make a small change in isPrime method. For instance if you check if 2 is a prime it will say no, when in fact 2 is a prime number.

Using IsPrime method in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This is my code to use IsPrime method to determine total number of primes between 0 and 1000 and print the total number of primes at last. Can anyone tell what's wrong with the code.
public static void main(String[] args) {
int z=0;
// z is the variable that holds total number of primes
//n is divisor
//i is dividend
if (isPrime(i)) {
z++;
}
System.out.print(z+"\n");
}
public static boolean isPrime(int n){
{
for(i=0; i<1000; i++)
{
for(n=0; n<i; n++)
if(i%n==0)
return false;
else
return true;
}
}
}
Thanks in advance
Formatting it might help you discover the error.
I see a few things that's wrong with your code:
From what I can see, you have an extra open curly bracket in your isPrime method.
i isn't declared in your main method.
You need to wrap your if(isPrime(i)) statement inside a for loop that goes from 0 to 1000. Like the following:
for (int i = 0; i <= 1000; i++) {
if (isPrime(i))
z++;
}
That way, it will be actually checking all the prime numbers from 0 to 1000
For good coding practices, I would name your z variable to be something like counter so that it's clear what that variable is supposed to be doing. i in for-loop is okay since that's a common way to index through the loop.
You can also use several tactics to optimize your code. You can use Math.sqrt() function, as well as start your for loop from 3 and go up by increment of 2 (since any even number will be dividable by 2) and initialize your counter from 1 since 2 will already be a prime number.
public static boolean isPrime(int n){
int factors = 0;
for(int i = 1; i <= n; i++){
if(n % i == 0) // ensure that you mod n not i
factors++;
}
// if factors count is equals to 2 then it is prime number else it's not prime number
if(factors == 2)
return true;
else
return false;
}
Check this modified code once for your reference.
I think you had a few things turned around.
Why not loop from 1 to 1000 in your primary function and then use the isPrime function to determine if each number is prime.
In the isPrime function, you count from 2 to 1/2 the value of the number and do the divisions to determine if it is prime. Return False if it is divisible.
public static void main(String[] args) {
int z=0;
for (i=1;i<=1000;i++) {
if (isPrime(i))
{
z++;
}
}
System.out.print(z+"\n");
}
public static boolean isPrime(int n){
for(i=2; i<=n/2; i++)
{
if(n%i==0) return false;
}
return true;
}
This will count the number of primes based on this link and your original answer...
public static void main(String[] args) {
int isPrimeCount = 0;
for(i=0; i<1000; i++)
{
if(Check_Prime(i))
{
isPrimeCount++;
}
System.out.println(isPrimeCount);
}
}
private static boolean Check_Prime(int number) {
int i;
for (i = 2; i <= number - 1; i++)
{
if (number % i == 0)
{
return false;
}
}
if (i == number)
{
return true;
}
return false;
}
You need to define the variable "i" before you pass it to the isPrime() method in main(). It seems as though whoever wrote the code did not fully understand what a prime number was. According to wikipedia "A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. " With this in mind you need to make sure that the value you pass to the isPrime() method is greater than 1. After look at your code I made some changes. I made the isPrime() method return false if the input value is <=1. Also, I made the isPrime() method return true if the input value is 2. I made other changes in the code that would make the for statement operate n-1 times because that is all that is needed to find out if the number is prime because all numbers are divisible by themselves. Also the for statement starts at the value 2. Your if-then-else return statements within the for loop is illogical because it will return a value without going through the entire loop. You did not need the inner for loop.
Here's a link on prime numbers
Here is the new code:
public class AreaComparison {
/**
* Starts the program.
*
* #param command line arguments
*/
public static void main(String[] args) {
int z = 0;
int i = 2;
// z is the variable that holds total number of primes
//n is divisor
//i is dividend
if (isPrime(i)) {
z++;
}
System.out.print(z + "\n");
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
if(n == 2){
return true;
}
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}

Implementing Euclid's Algorithm in Java

I've been trying to implement Euclid's algorithm in Java for 2 numbers or more.The problem with my code is that
a) It works fine for 2 numbers,but returns the correct value multiple times when more than 2 numbers are entered.My guess is that this is probably because of the return statements in my code.
b) I don't quite understand how it works.Though I coded it myself,I don't quite understand how the return statements are working.
import java.util.*;
public class GCDCalc {
static int big, small, remainder, gcd;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Remove duplicates from the arraylist containing the user input.
ArrayList<Integer> listofnum = new ArrayList();
System.out.println("GCD Calculator");
System.out.println("Enter the number of values you want to calculate the GCD of: ");
int counter = sc.nextInt();
for (int i = 0; i < counter; i++) {
System.out.println("Enter #" + (i + 1) + ": ");
int val = sc.nextInt();
listofnum.add(val);
}
// Sorting algorithm.
// This removed the need of conditional statements(we don't have to
// check if the 1st number is greater than the 2nd element
// before applying Euclid's algorithm.
// The outer loop ensures that the maximum number of swaps are occurred.
// It ensures the implementation of the swapping process as many times
// as there are numbers in the array.
for (int i = 0; i < listofnum.size(); i++) {
// The inner loop performs the swapping.
for (int j = 1; j < listofnum.size(); j++) {
if (listofnum.get(j - 1) > listofnum.get(j)) {
int dummyvar = listofnum.get(j);
int dummyvar2 = listofnum.get(j - 1);
listofnum.set(j - 1, dummyvar);
listofnum.set(j, dummyvar2);
}
}
}
// nodup contains the array containing the userinput,without any
// duplicates.
ArrayList<Integer> nodup = new ArrayList();
// Remove duplicates.
for (int i = 0; i < listofnum.size(); i++) {
if (!nodup.contains(listofnum.get(i))) {
nodup.add(listofnum.get(i));
}
}
// Since the array is sorted in ascending order,we can easily determine
// which of the indexes has the bigger and smaller values.
small = nodup.get(0);
big = nodup.get(1);
remainder = big % small;
if (nodup.size() == 2) {
recursion(big, small, remainder);
} else if (nodup.size() > 2) {
largerlist(nodup, big, small, 2);
} else // In the case,the array only consists of one value.
{
System.out.println("GCD: " + nodup.get(0));
}
}
// recursive method.
public static int recursion(int big, int small, int remainder) {
remainder = big % small;
if (remainder == 0) {
System.out.println(small);
} else {
int dummyvar = remainder;
big = small;
small = dummyvar;
recursion(big, small, remainder);
}
return small;
}
// Method to deal with more than 2 numbers.
public static void largerlist(ArrayList<Integer> list, int big, int small, int counter) {
remainder = big % small;
gcd = recursion(big, small, remainder);
if (counter == list.size()) {
} else if (counter != list.size()) {
big = gcd;
small = list.get(counter);
counter++;
largerlist(list, gcd, small, counter);
}
}
}
I apologize in advance for any formatting errors etc.
Any suggestions would be appreciated.Thanks!
I think these two assignments are the wrong way around
big = gcd;
small = list.get(counter);
and then big not used
largerlist(list, gcd, small, counter);
Also you've used static variables, which is usually a problem.
I suggest removing static/global variables and generally don't reuse variables.
Edit: Oh yes, return. You've ignored the return value of the recursion method when called from the recursion method. That shouldn't matter as you are printing out instead of returning the value, but such solutions break when, say, you want to use the function more than once.

Prime Number code

Let me start off by saying that I know there are many questions about prime numbers, this is more about my code and, specifically, the Boolean statements.
public class SumPrime
{
public static void main(String[] args) {
int top = inputInt("enter the number please");
int sum;
if (top > 2) {
sum = 2;
} else {
sum = 0;
}
int i;
int l;
for(l=3; l<top; l+=2){
boolean k = test(l);
String r;
if(k = true){
sum=sum+l;
output(l);
}else {
sum=sum;
}
}
System.out.println("The sum is " + sum);
}
static boolean test(int v) {
if (v%2==0)
return false;
for(int i=3; i<v; i+=2) {
if(v%i==0)
return false;
}
return true;
}
I am trying to code a program that will give me the sum of primes below an input value.
Below the above code, I have Input/Output statements, so that is not a problem. This code seems, to me at least, that it should work without a problem. I am relatively new to java, and very new to boolean variables and statements, so there could easily be a problem in that. (I searched for an answer, found nothing)
The test subprogram is supposed to check to see if a number is prime, and return true if it is, false if it is not. It seems to be returning true for every value, even for numbers that are not prime. The program returns a sum of 26, rather than 17 If i input 10 as the upper limit. It seems to be including every odd number even though it is supposed to check for primes.
I cannot figure out why this code does not work. Like I said, I think the error has something to do with the boolean method.
if you test 9 with this i < 9 is tested.
when i = 9 the for loop aborts and it returns true
static boolean test(int v) {
if (v%2==0)
return false;
for(int i=3; i<v; i+=2) {
if(v%i==0)
return false;
}
return true;
}
Edit:
also you should never test for primes above half the target number and the ideal maximum is sqrt(x) + 1
Your problem has nothing to do with your boolean method. Your condition is bad. You are performing an assignment in the conditional rather than actually testing equality. As a result, it always evaluates to true, and you end up adding where you shouldn't.
Do this instead:
if (k) {
sum += l;
}
Incidentally, sum = sum doesn't so anything and should be removed too.

Prime Tester for speed

I was given a homework assignment in Java to create classes that find Prime number and etc (you will see in code better).
My code:
class Primes {
public static boolean IsPrime(long num) {
if (num%2==0){
return false;
}
for (int i=3; i*i<=num;i+=2) {
if (num%i==0) {
return false;
}
}
return true;
} // End boolen IsPrime
public static int[] primes(int min, int max){
int counter=0;
int arcount=0;
for (int i=min;i<max;i++){
if (IsPrime(i)){
counter++;
}
}
int [] arr= new int[counter];
for (int i=min;i<max;i++){
if (IsPrime(i)){
arr[arcount]=i;
arcount++;
}
}
return arr;
} // End Primes
public static String tostring (int [] arr){
String ans="";
for (int i=0; i<arr.length;i++){
ans= ans+arr[i]+ " ";
}
return ans;
}
public static int closestPrime(long num){
long e = 0 , d = 0 , f = num;
for (int i = 2; i <= num + 1 ; i++){
if ((num + 1) % i == 0){
if ((num + 1) % i == 0 && (num + 1) == i){
d = num + 1;
break;
}
num++;
i = 1;
}
}
num = f;
for (int i = 2; i < num; i++){
if ((num - 1) % i == 0){
if ((num - 1) % i == 0 && (num - 1) == i){
e = num - 1;
break;
}
num--;
i = 1;
}
}
num = f;
if (d - num < num - e) System.out.println("Closest Prime: "+d);
else System.out.println("Closest Prime: "+e);
return (int) num;
} // End closestPrime
}//end class
The goal of my code is to be faster (and correct). I'm having difficulties achieving this. Suggestions?
**New code:
class Primes {
public static boolean IsPrime(int num) {
if (num==1){
return false;
}
for (int i=2; i<Math.sqrt(num);i++) {
if (num%i==0) {
return false;
}
}
return true;
}
// End boolen IsPrime
public static int[] primes(int min, int max){
int size=0;
int [] arrtemp= new int[max-min];
for (int i=min;i<max;i++){
if (IsPrime(i)){
arrtemp[size]=i;
size++;
}
}
int [] arr= new int[size];
for (int i=0;i<size;i++){
arr[i]=arrtemp[i];
}
return arr;
}
public static String tostring (int [] arr){
String ans="";
for (int i=0; i<arr.length;i++){
ans= ans+arr[i]+ " ";
}
return ans;
}
public static int closestPrime(int num) {
int count=1;
for (int i=num;;i++){
int plus=num+count, minus=num-count;
if (IsPrime(minus)){
return minus;
}
if (IsPrime(plus)) {
return plus;
}
count=count+1;
}
} // End closestPrime
}//end class
I did try to make it a bit better. what do you think, it can be improved more? (the speed test is still high...)
In your primes function you:
Check if the current number is divisible by two
Check to see if it's prime
Create an array to put your output in.
Check every number in the range again for primality before putting it in your array.
The problem is in the last step. By double-checking whether each number is prime, you're duplicating your most expensive operations.
You could use a dynamic data structure and add prime numbers to it as you find them. That way you only need to check once.
Alternatively, you could create a boolean array which is the size of your input range. Then as you find primes, set the corresponding array value to true.
UPDATE:
There are still a number of improvements you can make, but some will require more work than others to implement. Look at the specifics of your test and see what fits your needs.
Low-hanging fruit:
Use an ArrayList to collect primes as you find them in primes, as opposed to looping over the values twice.
In closestPrime, you're checking every single value on either side of num: half of these are even, thus not prime. You could adapt your code to check only odd numbers for primality.
Trickier to implement:
Try a more advanced algorithm for IsPrime: check out the Sieve of Eratosthenes
Above all, you should spend some time figuring out exactly where the bottlenecks are in your code. Oftentimes performance problems are caused by code we thought was perfectly fine. You might consider looking into the code-profiling options available in your development environment.
You make quite a few calls to isPrime(), each of which is very expensive. Your first step should be to minimize the number of times you do that, since the result doesn't change for any given number, there's no point calling more than once. You can do this with memoization by storing the values once they're computed:
ArrayList<Integer> memoList = new ArrayList<Integer>();
for(int i = 0; i < max; i++) {
if(isPrime(i)) {
memoList.add(i);
}
}
Now memoList holds all the primes you need, up to max, and you can loop over them rapidly without needing to recompute them every time.
Secondly, you can improve your isPrime() method. Your solution loops over every odd number from 3 to sqrt(n), but why not just loop over the primes, now that we know them?
public static boolean IsPrime(long num) {
for(int p : memoList) {
if(num % p == 0) {
return false;
}
}
return true;
}
These changes should dramatically improve how quickly your code runs, but there has been a lot of research into even more efficient ways of calculating primes. The Wikipedia page on Prime Numbers has some very good information on further tactics (prime sieves, in particular) you can experiment with.
Remember that as this is homework you should be sure to cite this page when you turn it in. You're welcome to use and expand upon this code, but not citing this question and any other resources you use is plagiarism.
I see a couple problems with your answer. First, 2 is a prime number. Your first conditional in IsPrime breaks this. Second, in your primes method, you are cycling through all number from min to max. You can safely ignore all negative numbers and all even numbers (as you do in IsPrime). It would make more sense to combine these two methods and save all the extra cycles.

Categories