Finding factors of integers - java

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

Related

prime number NOT working for certain values

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.

How to find the largest integer (n), such that n^3 < 12,000, using a while loop

This is what I have so far. The idea is it's supposed to increase n until n^3 is less than 12000, and print out n at the highest integer below 12k.
public static void main(String[] args) {
int n = 0;
int nCubed = (int) (Math.pow(n, 3));
while (nCubed < 12000) {
n++;
}
System.out.println("The highest integer below 12000 is " +n);
}
}
You need to set the nCubed value each time in the loop:
public static void main(String[] args) {
int n = 0;
int nCubed = (int) (Math.pow(n, 3));
while (nCubed < 12000) {
n++;
nCubed = (int) (Math.pow(n, 3));
}
System.out.println("The highest integer below 12000 is " +(n-1));
}
public class newClass{
public static void main(String[] args) {
int largestValue=0;
int n=0;
while(Math.pow(n,3)<12000) {
if(n>largestValue)
largestValue=n;
n++;
}
System.out.println(largestValue);
}
}
public class Loops_13
{
public static void main(String[] args)
{
int n = 0;
while (Math.pow(n,3) < 12000)
{
if (Math.pow(n + 1,3) >= 12000)
break;
n++;
}
System.out.println("The largest integer n such that n^3 is less than 12,000 is " + n);
}
}
//Find the largest n
public class Pb5 {
public static void main(String[] args) {
int n=0;
while(true) {
if(n*n*n<12000) {
n++;
}
else
break;
}
System.out.println("The largest integer n less than 12000 is:: "+(n-1));
}
}

Find test-case for which code does't work

I submitted one code in code chef but it's giving wrong answer even if it's correct
can anybody help me to identify that please.
I have tried so many inputs and calculated manually and they are correct so why they gave me wrong answer.
so,anybody who can find the TEST Case which give incorrect output by this code ?.
Here is Problem definition.
import java.util.Scanner;
import java.lang.Math;
class Codechef {
static int get(int n,int i,int digit)
{
int p;
p=(int)Math.pow(10,i-1);
n=n/p;
return n%10;
}
static boolean check_pal(int n)
{
int digit;
digit=(int) (Math.log10(n)+1);
int a=0,b=0,i,j,p;
int sum=0;
for(i=1,j=digit-1 ; i<=digit ; i++,j-- )
{
a=get(n,i,digit);
sum+=a*Math.pow(10,j);
}
if(sum==n)
return true;
else
return false;
}
static int reverse(int n)
{
int digit;
digit=(int) (Math.log10(n)+1);
int a=0,b=0,i,j,p;
int sum=0;
for(i=1,j=digit-1 ; i<=digit ; i++,j-- )
{
a=get(n,i,digit);
sum+=a*Math.pow(10,j);
}
return n+sum;
}
public static void main(String[] args) {
try{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
if(n<10 || n>999){
System.out.println("NONE");
return;
}
boolean c;
for(int i=1 ; i<=100 ; i++)
{
c=check_pal(n);
if(c==true)
{
System.out.println(n);
return;
}
n=reverse(n);
}
System.out.println("NONE");
}
catch(Exception e)
{
System.out.println("NONE");
}
}
}
Here is one more output.
for 99 it gives 99 and which is correct as it's palindrome.
For 89 (or 98 for that matter), your code returns "NONE", although you reach the answer 8813200023188 after only 24 steps.
Another case is that for 177 and 276 you should get 8836886388 instead of NONE
I didn't debug your code, I just wrote a program that does the same, and compared the output my program gave to the one your program gave. Since you just requested a testcase, that should suffice :) My gutfeeling is that you overflow... an int is not large enough to hold the answer in all cases.
Happy bughunting.
Edit (on Request) with my code.
I didn't change your code, except that I extracted your logic into a getResult(integer) methode so that I could bypass the scanning of the input and simply return a string as result. It prints out all the differences between our versions. I used BigInteger as the type to hold my results.
public class Main {
public static void main(String[] args) {
Main m = new Main();
for (int i=10; i < 1000; i++) {
String myResult = null;
String hisResult = null;
try {
myResult = m.getResultAsString(i);
} catch (Exception e){
System.out.println("Your code threw an exception for " + i);
}
try{
hisResult = Codechef.getResult(i);
} catch (Exception e){
System.out.println("His code threw an exception for " + i);
}
if (myResult != null && hisResult != null && ! myResult.equals(hisResult)) {
System.out.println("For " + i + " you have " + myResult + " but he has " + hisResult);
}
}
}
public String getResultAsString(int inputNumber) {
BigInteger res = getResultAsBigInteger(new BigInteger(""+inputNumber));
if (res != null) {
return res.toString();
} else {
return "NONE";
}
}
public BigInteger getResultAsBigInteger(BigInteger inputNumber) {
int numberOfSteps = 0;
BigInteger currentValue = inputNumber;
while (numberOfSteps < 101 && ! isPalindrome(currentValue)) {
numberOfSteps++;
currentValue = currentValue.add(reverseDigits(currentValue));
}
return numberOfSteps < 101 ? currentValue : null;
}
public boolean isPalindrome(BigInteger number) {
return number.equals(reverseDigits(number));
}
public BigInteger reverseDigits(BigInteger input) {
String inputString = input.toString();
String output = "";
for (int i = inputString.length() - 1; i >= 0; i--)
{
output += inputString.charAt(i);
}
return new BigInteger(output);
}
}
There is an overflow error in your code.
for input 89 it's not working as #Yves V. said
Suggestion is to use BigInteger class of lang.Match it will be useful to eliminate this overflow error.

printing fibonacci number series without using loops

Is there a hack to print the first n fibonacci numbers without calling a loop
for(int i=1; i<n; i++)
System.out.println(computeF(n));
from the main program?
public static int computeF(int n)
{
if(n==0)
{
return 0;
}
else if(n==1)
{
return 1;
}
else
{
return computeF(n-1)+computeF(n-2);
}
}
There might be a way to print the intermediate values in recursion which will print the fibonacci numbers.
You could use tail recursion.
public class Fid
{
static int n1=0;
static int n2=1;
static int nex=0;
public static void fb(int n)
{
if(n<10)
{
if(n==0)
{
System.out.print(" "+n);
n++;
fb(n);
}
else
if(n==1)
{
System.out.print(" "+n);
n++;
fb(n);
}
else{
nex=n1+n2;
System.out.print(" "+nex);
n1=n2;
n2=nex;
n++;
fb(n);
}
}
}
public static void main(String[] args)
{
fb(0);
}
}
using recursion:-
class FibonacciRecursion
{
private static int index = 0;
private static int stoppingPoint = 9;
public static void main (String[] args)
{
int n1 = 0;
int n2 = 1;
fibonacciSequence(n1, n2);
}
public static void fibonacciSequence(int n1, int n2)
{
System.out.println("index: " + index + " -> " + n1);
// make sure we have set an ending point so this Java recursion
// doesn't go on forever.
if (index == stoppingPoint)
return;
// make sure we increment our index so we make progress
// toward the end.
index++;
fibonacciSequence(n2, n1+n2);
}
}
//Java program to print Fibonacci Series up to n terms given by user without using loop
import java.util.* ;
public class Fibonacci
{
public static void main(String[] arguments)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the no of terms :");
int no_of_terms= s.nextInt(),a=1,b=0,c=0,count=1;
System.out.print("0 ");//printing the first term
fib(no_of_terms,a,b,c,count);}
public static void fib(int no_of_terms,int a,int b,int c,int count)
{
//when value of count will be equal to the no of terms given by user the program will terminate
if (count==no_of_terms)
System.exit(0);
else
{
count++;
System.out.print(a+" ");
c=b;
b=a;
a=b+c;//calculating the next term
fib(no_of_terms,a,b,c,count);//calling the function again with updated value
}
}
}
import java.util.*;
public class Fibonacci{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a no.");
int n= sc.nextInt(),a=1,b=0,c=0;
num(n,a,b,c);
}
public static void num(int n,int a,int b,int c){
if(a<=n){
System.out.println(a);
c=b;
b=a;
a=b+c;
num(n,a,b,c);
}
}
}

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