prime number NOT working for certain values - java

The task is to find the prime number at a given number. Here is the code
import java.util.ArrayList;
public class Queue {
private static int number = 0;
private static int prime;
public static void calculatePrime(int p) {
while (prime <p) {
if (number % 2 != 0)
number++;
prime++;
{
number++;
}
}
System.out.println(number );
}
public static void main(String args[]) {
calculatePrime(10001);
}
}
when the input value is 3 it prints out the correct value of 5 but when the input value is 10001 it prints out a number other than 104743

Here's your calculatePrime method as the compiler sees it:
public static void calculatePrime(int p) {
while (prime <p) {
if (number % 2 != 0)
number++;
prime++;
number++;
}
System.out.println(number );
}
You could use something like this:
public static void calculatePrime(int p) {
int primeCandidate = p;
while (!isPrime(primeCandidate)) {
primeCandidate++;
}
System.out.println(number );
}
And you'll need a method to return true if the candidate is a prime. There are loads of these available for the small price of a google search.

Related

Variable Sample can not be resolved to variable

import java.util.Arrays;
import java.util.*;
import java.util.stream.Collectors;
// double the first even number greater than 3
public class FirstDouble {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,5,6,7,8,9);
/* int result = 0;
for(int e : numbers)
{
if(e>3 && e%2==0)
{
result = e*2;
break;
}
}
System.out.println(result);
*/
System.out.println(
numbers.stream()
.filter(Sample::isGT3)
.filter(Sample::isEven)
.map(Sample::doubleIt)
.findFirst());
}
public boolean isGt3(int number) {
return number > 3;
}
public boolean isEven(int number) {
return number % 2 == 0;
}
public int doubleIt(int number) {
return number * 2;
}
}
Three modifications are needed to make the code compile:
Rename Sample to FirstDouble in order to properly reference the class
Rename the method isGt3 to isGT3
As the methods are referenced statically, add the static modifier to isGT3, isEven and doubleIt
After that, it prints out Optional[12]. If only the number should be printed, add a get after findFirst.

Finding factors of integers

I tried to create a simple program that finds all divisors of a number. I was instructed to store every divisor into a string and use a while loop. I don't know why, but my program does not run. It compiles without errors, but gives no output.
import static java.lang.System.*;
public class Divisors
{
public static String getDivisors( int number )
{
String divisors="";
int n=1;
while(n < number)
{
if (number % n==0)
{
divisors +=" "+ n;
}
}
return number+ " has divisors:"+ divisors;
}
}
Here is my tester class:
import static java.lang.System.*;
public class Lab09f
{
public static void main( String args[] )
{
Divisors d = new Divisors();
out.println(d.getDivisors(10));
out.println(d.getDivisors(45));
out.println(d.getDivisors(14));
out.println(d.getDivisors(1024));
out.println(d.getDivisors(1245));
out.println(d.getDivisors(33));
out.println(d.getDivisors(65535));
}
}
while(n < number)
{
if (number % n==0)
{
divisors +=" "+ n;
}
n++;
}
return number+ " has divisors:"+ divisors;
}
you were not adding to your n so was looping forever
You need to increment n:
public class Divisors
{
public static String getDivisors( int number )
{
String divisors="";
int n=1;
while(n < number)
{
if (number % n==0)
{
divisors +=" "+ n++;
}
}
return number+ " has divisors:"+ divisors;
}
}

Illegal start of expression, not sure why

I'm a first year programmer and not completely certain on what I'm doing wrong with this code. Please, can anyone help?
package ________;
public class _______
{
public static void main(String[] args)
{
public int getFactorial(int number)
{
if (number == 1)
{
System.out.println("Returned 1");
return 1;
}
else
{
int factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
return factor;
}
}
}
}
This line displays an illegal start of expression method every time I attempt to compile or run the program:
public int getFactorial(int number)
The ____'s just represent the hidden package and class names. Using NetBeans IDE 7.4, Java apllication
You cannot have other methods or functions inside the main function. You can however call the functions from your main function.
Please write the code as
public static void main(String[] args)
{
int number = 10;
/* if you want user to input */
Scanner get = new Scanner(System.in);
number = get.nextInt(); // get the next integer user types :)
getFactorial(number);
}
public static int getFactorial(int number)
{
int factor = 1;
if (number == 1)
{
System.out.println("Returned 1");
}
else
{
factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
}
return factor;
}
This way, your function would be inside the same Class but outside the bounds of Main method. In the main method, you would be calling it and where the control would be transfering to the getFactorial function.
You have a method (getFactorial) inside another (main). They need to come one after another.
public static void main(String[] args){
getFactorial(int number);
}
public static int getFactorial(int number)
{
if (number == 1)
{
System.out.println("Returned 1");
return 1;
}
else
{
int factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
return factor;
}
}
You can't write a method inside another method. Your code should look like this:
package ________;
public class _______ {
public static void main(String[] args) {
//call getFactorial, for example
int result = getFactorial(2);
}
public static int getFactorial(int number) {
if (number == 1) {
System.out.println("Returned 1");
return 1;
} else {
int factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
return factor;
}
}
}

Trying to display factors of integers, but having difficulties

I'm new to programming, I'm not sure where I'm going wrong with this one.
Here is my main method:
import java.util.*;
public class DisplayFactors
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter a integer: ");
String input1 = scan.nextLine();
int input = Integer.parseInt(input1);
FactorGenerator factor = new FactorGenerator(input);
System.out.print(factor.getNextFactor());
while (!factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}
}
}
Here is my class:
public class FactorGenerator {
private int num;
private int nextFactor;
public FactorGenerator(int n)
{
num = nextFactor = n;
}
public int getNextFactor()
{
int i = nextFactor - 1 ;
while ((num % i) != 0)
{
i--;
}
nextFactor = i;
return i;
}
public boolean hasMoreFactors()
{
if (nextFactor == 1)
{
return false;
}
else
{
return true;
}
}
}
Currently if I enter 15 as the integer I only get one factor back, which is 5, but I need it to display all the factors: 15, 5, 3 and 1. Where am I going wrong?
When you use
while (!factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}
you say that while there aren't any more factors, print them on the screen, but you need
to print the factors as long as they exist in the list.
So in Java you will have:
while (factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}
while (!factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}
must be
while (factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}

Write a program to accept number from command line and display sum of digits in a number by using recursive funcion

I have written the code but it displays Stackoverflowerror message.
class Sum
{
int ans=0,temp,temp2;
int getsum(int no)
{
if(no>0)
{
temp=no % 10;
ans=ans + temp;
getsum(no/10);
}
else
{
return ans;
}
}
}
class recsum
{
public static void main(String args[])
{
Sum s=new Sum();
int no,len;
len=args.length;
if(len==0)
{
System.out.println("No argruments are given ! ");
}
else
{
no=Integer.valueOf(args[0]).intValue();
System.out.println("Sum of digits= " + s.getsum(no));
}
}
}
You are over-complicating things a lot in your code. Here is a simpler working example:
public static int getSum(final String[] args, final int index) {
if (index < args.length) {
return Integer.valueOf(args[index]) + getSum(args, index + 1);
} else {
return 0;
}
}
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("You need to provide numbers as arguments.");
}
final int sum = getSum(args, 0);
System.out.println("Sum: " + sum);
}
You are supposed to be recursive, this is in the getSum function, because it is calling itself with differing parameters.
In recursive functions, you always need to have an exit branch that causes the calling to stop.
As sums won't change if you add 0 this can be exploited for a very clean exit.
The Stack overflow is normally because you never bottom out of the recursion.
Change class Sum to this:
class Sum {
int ans = 0, temp = 0;
int getsum(int no) {
if((no/10)-.5 >= 1)
ans += getsum(no/10);
else
return ans;
}
}
I'm not completely sure if this will work, and I can't compile it right now. I think this is one way to do it, but again, I'm not completely sure.
Program: Write a program to use Command Line Arguments.
class Sumnum1
{
int i,t,num,sum=0;
void getData(String s)
{
num=Integer.parseInt(s);
}
int digitSum()
{
for(i=num;i>=1;i=i/10)
{
t=i%10;
sum=sum+t;
}
return sum;
}
public static void main(String arg[])
{
int ds=0;
Sumnum1 obj=new Sumnum1();
obj.getData(arg[0]);
ds=obj.digitSum();
System.out.println("sum of digit="+ds);
}
}
BY :ANKIT AGRAWAL (A.A.)

Categories

Resources