Ex: n1=100, n2=250, out=233.
Here I have to find the largest odd fibonacci number in the given set of ranges. If an odd fibonacci number doesn't exist then it should return 0. I am getting output as 50 times 0's and then 10 times 233. Where is my mistake and how can I get the desired output?
public class Fibo {
public static void main(String[] args) {
try {
int n1 = 100;
int n2 = 250;
int res = 0;
if (n1 % 2 == 0) {
n1 += 1;
for (int i = n1; i < n2; i += 2) {
if (isPerfectSquare(5 * i * i + 4) || isPerfectSquare(5 * i * i - 4))
res = i;
System.out.println(res);
}
}
} catch(Exception ignored) {
System.out.println("0");
}
}
public static boolean isPerfectSquare(int num) {
double sqrt = Math.sqrt(num);
int x = (int)sqrt;
return Math.pow(sqrt, 2) == Math.pow(x, 2);
}
}
public class Fibonacci {
public static void main(String[] args) {
System.out.println("Enter the starting range");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println("Enter the ending range");
int r = sc.nextInt();
int res = 0;
for (int i = n; i <= r; i++) {
if (isPerfectSquare(5 * i * i + 4) || isPerfectSquare(5 * i * i - 4))
res = i;
}
System.out.println("The biggest odd number in the range is"+" "+res);
}
public static boolean isPerfectSquare(int num) {
double sqrt = Math.sqrt(num);
int x = (int)sqrt;
return Math.pow(sqrt, 2) == Math.pow(x, 2);
}
}
public static int getLargestOddFibonacciBetween(int lo, int hi) {
assert lo <= hi;
int f0 = 0;
int f1 = 1;
int res = -1;
while (f1 <= hi) {
int val = f0 + f1;
f0 = f1;
f1 = val;
if (val >= lo && val <= hi && isOdd(val))
res = val;
}
return res;
}
private static boolean isOdd(int val) {
return (val & 1) == 1;
}
Related
public class Amstrong {
public static void main(String[] args) {
for (int i = 100; i < 1000; i++) {
String a = String.valueOf(i);
int b = a.charAt(0);
int c = a.charAt(1);
int d = a.charAt(2);
int e = b * b * b + c * c * c + d * d * d;
if (e == i) {
System.out.println(i);
}
}
}
}
//Help me out please, no error occurred but the result returned in the blank
You are not converting the characters to digits correctly.
One of the possible ways to fix it:
int b = a.charAt(0)-'0';
int c = a.charAt(1)-'0';
int d = a.charAt(2)-'0';
Another way:
int b = Character.digit (a.charAt(0),10);
int c = Character.digit (a.charAt(1),10);
int d = Character.digit (a.charAt(2),10);
Either way will give your the output:
153
370
371
407
Another way you can do it is:
import java.util.*;
public class ArmstrongNumber3
{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter any number");
int n = sc.nextInt();
int b = n;
int sum = 0;
int d = 0;
while (n != 0) {
d = n % 10;
sum += (d * d * d);
n = n / 10;
}
if (sum == b) {
System.out.println("Armstrong");
} else
{
System.out.println("Not Armstrong");
}
}
}
import java.util.Scanner;
public class Amstrong {
public static void main(String args[]) {
Integer num, temp, len = 0, initVal;
double finalVal = 0;
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number");
num = scn.nextInt();
initVal = num;
temp = num;
while (temp != 0) {
temp = temp / 10;
len++;
}
for (int i = 0; i <= len; i++) {
temp = num % 10;
finalVal = finalVal + Math.pow(temp, len);
num = num / 10;
}
if (Double.valueOf(initVal) == finalVal) {
System.out.println("Amstrong");
} else {
System.out.println("Not Amstrong");
}
}
}
public class Palindrome {
public static void main(String args[]) {
int x = 121;
int res = 0;
while (x > 0) {
res = res * 10 + (x % 10);
x /= 10;
}
if (x - res == 0) {
System.out.println("True" + res);
} else
System.out.println("False" + res);
}
}
Hello! This code is to check if an integer is a palindrome without converting the int to a String. For some reason, the computer thinks res is not same as x though both represent the number 121. Appreciate your help and thanks in advance!
You were close. Here is a solution building on what you did:
static bool isPalindrome (int n1, int n2) {
return getReverseInteger(n1) == n2;
}
static int getReverseInteger (int n) {
int nReversed = 0;
while (n > 0) {
int digit = n % 10;
nReversed = nReversed * 10 + digit;
n = (n - digit) / 10;
}
return nReversed;
}
I am new in java and I have got assigment with armstrong numbers.
I am already created new class ArmstrongNumber.java where I initialized method from this website: http://www.programmingsimplified.com/java/source-code/java-program-armstrong-number
Now in a class where is main method I created another method where I am calling ArmstrongNumber class and now I have to return armstrong number from interval from [100 till 999].
There is where I am stuck now .
public static void armtrongNumbs()
{
ArmstrongNumber returnObj = new ArmstrongNumber(); // here i m calling class.
int start = 100;
int end = 999;
for(int i = start; i<= end; i++)
{
number = i + number;
returnObj.Armstrong(number);
}
//returnObj.Armstrong();
}
How could my loop return only armstrong numbers?
Edit: ArmstrongNumber class
class ArmstrongNumber
{
public void Armstrong(int number)
{
int n, sum = 0, temp, remainder, digits = 0;
Scanner in = new Scanner(System.in);
System.out.println("Input a number to check if it is an Armstrong number");
n = in.nextInt();
temp = n;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
System.out.println(n + " is an Armstrong number.");
else
System.out.println(n + " is not an Armstrong number.");
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
}
Based on your requirement, you need logic of ArmstrongNumber.java and mold it to suit as per your requirements.
You just need to use the following code and can stop worrying about using ArmstrongNumber.java
package hello;
public class Abc {
public static void main(String[] args) {
int n, sum, temp, remainder, digits;
int start = 100;
int end = 999;
for (int i = start; i <= end; i++) {
sum = 0;
digits = 0;
temp = i;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp / 10;
}
temp = i;
while (temp != 0) {
remainder = temp % 10;
sum = sum + power(remainder, digits);
temp = temp / 10;
}
if (i == sum)
System.out.println(i + " is an Armstrong number.");
}
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p * n;
return p;
}
}
Here you can see, how the sum and digits are initialised to zero for every number and then the rest of logic is same. You can verify that 153, 370, 371, 407 are printed as Armstrong numbers.
Hope this helps
try like
public int[] Armstrong(int start ,int end){
int a[],i=0;
for(int i = start; i<= end; i++)
{
number = i + number;
int n, sum = 0, temp, remainder, digits = 0;
Scanner in = new Scanner(System.in);
System.out.println("Input a number to check if it is an Armstrong number");
n = in.nextInt();
temp = n;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
a[i++]=n;
else
System.out.println(n + " is not an Armstrong number.");
}
return a;
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p * n;
return p;
}
}
I'm trying to do the Algorithm programming assignment of Princeton , and I met a problem about the memory test. The assignment requires us run the percolation program N times and find the medium of the result, and I write a percolationtest.java and for each time, I create an instance variable, it worked, but use too much memory, and the instructor suggests me to use local variable, but I don't know how. Can some one help me and give me some advice, I really appreciate it.
public class PercolationStats {
private int N, T, totalSum;
private double []fraction;
private int []count;
public PercolationStats(int N, int T) {
if (N <= 0 || T <= 0)
throw new IllegalArgumentException();
else {
this.N = N;
this.T = T;
count = new int [T];
totalSum = N*N;
fraction = new double[T];
int randomX, randomY;
for (int i = 0; i < T; i++) {
Percolation perc = new Percolation(N);
while (true) {
if (perc.percolates()) {
fraction[i] = (double) count[i]/totalSum;
break;
}
randomX = StdRandom.uniform(1, N+1);
randomY = StdRandom.uniform(1, N+1);
if (perc.isOpen(randomX, randomY)) continue;
else {
perc.open(randomX, randomY);
count[i]++;
}
}
}
}
} // perform T independent experiments on an N-by-N grid
public double mean() {
double totalFraction = 0;
for (int i = 0; i < T; i++) {
totalFraction += fraction[i];
}
return totalFraction/T;
} // sample mean of percolation threshold
public double stddev() {
double u = this.mean();
double sum = 0;
for (int i = 0; i < T; i++) {
sum += (fraction[i] - u) * (fraction[i] - u);
}
return Math.sqrt(sum/(T-1));
} // sample standard deviation of percolation threshold
public double confidenceLo() {
double u = this.mean();
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u-1.96*theta/sqrtT;
} // low endpoint of 95% confidence interval
public double confidenceHi() {
double u = this.mean();
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u+1.96*theta/sqrtT;
} // high endpoint of 95% confidence interval
public static void main(String[] args) {
int N = 200;
int T = 100;
if (args.length == 1) N = Integer.parseInt(args[0]);
else if (args.length == 2) {
N = Integer.parseInt(args[0]);
T = Integer.parseInt(args[1]); }
PercolationStats a = new PercolationStats(N, T);
System.out.print("mean = ");
System.out.println(a.mean());
System.out.print("stddev = ");
System.out.println(a.stddev());
System.out.print("95% confidence interval = ");
System.out.print(a.confidenceLo());
System.out.print(", ");
System.out.println(a.confidenceHi());
}
}
public class Percolation {
private boolean[][] site;
private WeightedQuickUnionUF uf;
private int N;
public Percolation(int N) {
if (N < 1)
throw new IllegalArgumentException();
else {
site = new boolean[N + 2][N + 2];
for (int j = 1; j <= N; j++) {
site[0][j] = true;
site[N + 1][j] = true;
}
uf = new WeightedQuickUnionUF((N + 2) * (N + 2));
for (int i = 1; i <= N; i++) {
uf.union(0, i);
}
this.N = N;
}
}
public void open(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else {
if (!site[i][j]) {
site[i][j] = true;
if (site[i - 1][j]) {
uf.union((N + 2) * (i - 1) + j, (N + 2) * i + j);
}
if (site[i + 1][j]) {
uf.union((N + 2) * i + j, (N + 2) * (i + 1) + j);
}
if (site[i][j + 1]) {
uf.union((N + 2) * i + (j + 1), (N + 2) * i + j);
}
if (site[i][j - 1]) {
uf.union((N + 2) * i + (j - 1), (N + 2) * i + j);
}
}
}
}
public boolean isOpen(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else
return site[i][j];
}
public boolean isFull(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else
return site[i][j] && (i == 1 || uf.connected((N + 2) * i + j, 0));
}
public boolean percolates() {
for (int i = 1; i <= N; i++) {
if (this.isFull(N, i)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
}
}
Added meanValue instance variable to keep mean value and replaced it in multiple places where you used to call mean() method which was over head to calculate again and again. Also modified "int[] count" as local variable which you were not using outside the constructor. post your "Percolation" and "StdRandom" classes for more optimization of code. you can run this code and test, it should reduce the runtime than yours.
public class PercolationStats {
private int N, T, totalSum;
private double []fraction;
private double meanValue;
public PercolationStats(int N, int T) {
if (N <= 0 || T <= 0)
throw new IllegalArgumentException();
else {
this.N = N;
this.T = T;
int [] count = new int [T];
totalSum = N*N;
fraction = new double[T];
int randomX, randomY;
for (int i = 0; i < T; i++) {
Percolation perc = new Percolation(N);
while (true) {
if (perc.percolates()) {
fraction[i] = (double) count[i]/totalSum;
break;
}
randomX = StdRandom.uniform(1, N+1);
randomY = StdRandom.uniform(1, N+1);
if (perc.isOpen(randomX, randomY)) continue;
else {
perc.open(randomX, randomY);
count[i]++;
}
}
}
}
}
// perform T independent experiments on an N-by-N grid
public double mean() {
double totalFraction = 0;
for (int i = 0; i < T; i++) {
totalFraction += fraction[i];
}
meanValue = totalFraction/T;
return meanValue;
} // sample mean of percolation threshold
public double stddev() {
double u = meanValue;
double sum = 0;
for (int i = 0; i < T; i++) {
sum += (fraction[i] - u) * (fraction[i] - u);
}
return Math.sqrt(sum/(T-1));
} // sample standard deviation of percolation threshold
public double confidenceLo() {
double u = meanValue;
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u-1.96*theta/sqrtT;
} // low endpoint of 95% confidence interval
public double confidenceHi() {
double u = meanValue;
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u+1.96*theta/sqrtT;
} // high endpoint of 95% confidence interval
public static void main(String[] args) {
int N = 200;
int T = 100;
if (args.length == 1) N = Integer.parseInt(args[0]);
else if (args.length == 2) {
N = Integer.parseInt(args[0]);
T = Integer.parseInt(args[1]); }
PercolationStats a = new PercolationStats(N, T);
System.out.print("mean = ");
System.out.println(a.mean());
System.out.print("stddev = ");
System.out.println(a.stddev());
System.out.print("95% confidence interval = ");
System.out.print(a.confidenceLo());
System.out.print(", ");
System.out.println(a.confidenceHi());
}
}
public class PalindromicPrimes {
public static void main (String[] args) {
userInt();
System.out.println("The palindromic primes less than " + userInt() +
" are:");
for (int i = 0; i <= userInt(); i++) {
if (isPrime() && isPalindrome()) {
System.out.println(i);
}
}
}
private static boolean isPrime() {
if (userInt() == 2 || userInt() == 3) {
return true;
}
if (userInt() % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(userInt()) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (userInt() % i == 0) {
return false;
}
}
return true;
}
private static boolean isPalindrome() {
if (userInt() < 0)
return false;
int div = 1;
while (userInt() / div >= 10) {
div *= 10;
}
while (userInt() != 0) {
int x = userInt();
int l = x / div;
int r = x % 10;
if (l != r)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
private static int userInt() {
Scanner s = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int userInt = s.nextInt();
return userInt;
}
}
is there a different way of getting the user input? or can I keep it this way?
when it runs it just keeps prompting the user input.
rearrange it like this:
public static void main (String[] args) {
//get it and save it here!
int userValue = userInt();
System.out.println("The palindromic primes less than " + userValue +
" are:");
for (int i = 0; i <= userValue; i++) {
if (isPrime(userValue) && isPalindrome(userValue)) {
System.out.println(i);
}
}
}
then also update all the methods that care about this "userInt" value.
Every time you call userInt() you're telling the code to get a new value from the command line.
Try this:
public static void main (String[] args) {
int value = userInt();
System.out.println("The palindromic primes less than " + value +
" are:");
for (int i = 0; i <= value; i++) {
if (isPrime() && isPalindrome()) {
System.out.println(i);
}
}
}
The term userInt() is a function invocation that prompts the user for input. Odds are you only want to do this once. You're doing it multiple times.
You should store the result of userInt() in a variable.
int typed = userInt();
And then use this variable to reference what the user typed instead of calling userInt() again.
System.out.println("The palindromic primes less than " + typed +
" are:");
for(int i = 0; i < typed; i++) ...
You keep calling userInt(). That is the problem.
I don't understand your logic. So I have not modified that code. But the code runs.
import java.util.Scanner;
public class PalindromicPrimes {
public static void main (String[] args) {
int x = userInt();
System.out.println("The palindromic primes less than " + x +
" are:");
for (int i = 0; i <= x; i++) {
if (isPrime(i) && isPalindrome(i)) {
System.out.println(i);
}
}
}
private static boolean isPrime(int a) {
if (a == 2 || a == 3) {
return true;
}
if (a % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(a) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (a % i == 0) {
return false;
}
}
return true;
}
private static boolean isPalindrome(int a) {
if (a < 0)
return false;
int div = 1;
while (a / div >= 10) {
div *= 10;
}
while (a != 0) {
int x = a;
int l = x / div;
int r = x % 10;
if (l != r)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
private static int userInt() {
Scanner s = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int userInteger = s.nextInt();
return userInteger;
}
}
Remember, don't use the same names for variable and function. In the function userInt(), you have used a variable int userInt, to get the result from the scanner. This might be aa recursive call sometimes. Be careful with that.