I am getting wrong results resolving below task:
Generalized harmonic numbers. Write a program GeneralizedHarmonic.java that takes two integer command-line arguments n and r and uses a for loop to compute the nth generalized harmonic number of order r, which is defined by the following formula:
formula
public class GeneralizedHarmonic {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int i;
double sum = 0;
for (i = 0; i <= a; i++) {
sum += 1 / Math.pow(i, b);
}
System.out.println(sum);
}
}
This is my code but I could not get the correct test output.The output result is always Infinity.
test outputs
You have initliazed int i = 0 in for-loop for (i = 0; i <= a; i++) and so the first element of your harmonic number isn't , but .
The code that works:
public class GeneralizedHarmonic {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
double sum = 0;
for (int i = 1; i <= a; i++) {
sum += 1 / Math.pow(i, b);
}
System.out.println(sum);
}
}
This is my code and I do not know why the answer after 12 are incorrect.
First i calculate the Factorial of input number then I have to show the least valuable digit.
public class q3411 {
public static int leastValuableDigit(int n) {
for(int i = 0; i < String.valueOf(n).length(); i++) {
int x = (int) Math.floor((n % Math.pow(10, i + 1)) / Math.pow(10, i));
if(x != 0) return x;
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int fon = 1;
for(int i = 1; i <= n; i++) fon *= i;
System.out.println((leastValuableDigit(fon)));
}
}
First, I changed the algorithm of finding the factorial for more numbers.
The algorithm of finding the required number can be changed by removing all 0 from the factorial and taking the last of its bytes.
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static byte leastValuableDigit(BigInteger n) {
String num = String.valueOf(n).replaceAll("0", "");
return Byte.parseByte(String.valueOf(num.charAt(num.length() - 1)));
}
public static BigInteger getFactorial(int f) {
if (f <= 1) {
return BigInteger.valueOf(1);
}
else {
return BigInteger.valueOf(f).multiply(getFactorial(f - 1));
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
BigInteger fon = getFactorial(n);
System.out.println((leastValuableDigit(fon)));
}
}
Your algorithm is incorrect, cause you do a lot of unnecessary calculations and roundings
My Code doesn't print out Triangular Numbers according to the formula, but only loops the number 1.
What is my mistake?
public class Triangular{
public static void main(String[] args) {
int n = 1;
int t = (n * (n + 1)) / 2;
while(n <= 10) {
n++;
System.out.println(t);
}
}
}
Although you are increasing n by one, you are not recalculating the value of t inside the loop.
Try calculating the value of t inside the loop, for example:
public static void main(String[] args)
{
int n = 0;
int t = 0;
while (n <= 10)
{
n++;
t = (n * (n + 1))/2;
System.out.println(t);
}
}
Each time you increase the value of n, you need to recalculate the value of t by passing the new value of n into the formula.
t is not recalculated when n changes. You need to assign it inside the while loop. Also, you may as well just do this:
public class Triangular {
public static void main(String[] args) {
int n = 1;
int t = 1;
while(n <= 10) {
System.out.println(t);
n++;
t += n;
}
}
}
I am trying to find out the sum of the series, 1/2! - 2/3! + 3/4! - 4/5! ... n. Sorry if this sounds awkward but the sum always shows up as 0.0. I can't figure out what's happening and I am just starting out. Can anyone kindly point out the mistake and suggest how to fix it? Thanks!
import java.util.Scanner;
public class Series {
/*
* Series design: 1/2! - 2/3! + 3/4! - 4/5! .. n
*/
static double sum = 0; static int n;
Scanner sc = new Scanner(System.in);
public static int fact(int n){
int fact = 1;
for (int i = 1; i<=n; i++){
fact *= i;
}
return fact;
}
void generate(){
double sign = 1.0; double term;
for (int i = 1; i<=n; i++){
term = i/fact(i+1) * sign;
sum += term;
sign *= -1;
}
}
void accept(){
System.out.println("Enter the value of n:");
n = sc.nextInt();
}
public static void main(String[] args){
Series o = new Series();
o.accept();
o.generate();
System.out.println("The sum of the series is: " +sum);
}
}
i and fact(i+1) are both ints, so you're performing integer division. Since i < fact(i+1), each such term will produce a zero.
You had the right idea with defining sign as a double, but since / and * have the same precedence, you're first performing an integer division and only then multiplying by the double sign. Moving it to the beginning of the expression should do the trick:
void generate(){
double sign = 1.0; double term;
for (int i = 1; i<=n; i++){
term = (sign * i) / fact(i+1);
sum += term;
sign *= -1;
}
}
Your problem is that i/fact(i+1) is an int division, so it is truncated to 0 (since it's smaller than 1).
Change it to (double)i/fact(i+1).
Alternately, you can write
term = sign*i/fact(i+1);
since sign is already double, so it would ensure sign*i would also be double, and the division would be a floating point division.
import java.util.Scanner;
public class Series {
static double sum = 0.0;
static int n=0;
static Scanner sc = new Scanner(System.in);
public static int fact(int n)
{
int fact = 1;
for(int i = 1; i<=n; i++){
fact *= i;
}
return fact;
}
static void generate(){
//because of static property
double sign = 1.0; double term;
for(int i = 1; i<=n; i++){
term = (i* sign)/fact(i+1) ;
sum += term;
sign *= -1;
}
}
static void accept(){
//because of static property
System.out.println("Enter the value of n:");
n = sc.nextInt();
}
public static void main(String[] args){
Series.accept();
Series.generate();
System.out.println("The sum of the series is: " +sum);
}
}
I tried making a Java program executing the Fibonacci sequence.
Here's my code:
import java.io.*;
public class Fibonacci{
public static void main(String[]args){
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int ctr1=0;
int ctr2=0;
int num1=0;
int num2=0;
int num3=0;
try{
System.out.println("How many numbers would you want to see?");
ctr2=Integer.parseInt(Data.readLine());
for(int ans=0; ctr1==ctr2; ctr1++){
num1++;
System.out.println(num2 + "\n" + num1);
ans=num1+num2;
System.out.println(ans);
ans=num3;
}
}catch(IOException err){
System.out.println("Error!" + err);
}catch(NumberFormatException err){
System.out.println("Invald Input!");
}
}
}
Obviously, I'm a beginner in Java and I don't know how to properly use the for statement. Would somebody be kind enough to make my code work? Or maybe make a way shorter code that works. I'm a beginner so be cool. Thanks :)
Fibonacci series in java is actually quite simple and can be done with just one single for-loop!!!!
import java.io.*;
class fibonacci{
public static void main() throws NumberFormatException, IOException{
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int a,b,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=Integer.parseInt(Data.readLine());
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
This has been done using buffered reader........ If you are said to use only bufferedreader go for this else you can use Scanner class which is much simple and easy to use because you don't have to catch or throw any exceptions.....
Scanner program:-
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a,b,c;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
Now as I said in one loop you can do it.... Here is another method where you do the swapping inside the body of the loop and not in the arguments of it...
And this is much simplier to understand for beginners as u don't have to pass multiple variables inside the arguments and yeah its a bit longer
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a = 0,b = 1,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
System.out.println(a +"\n" +b);//\n is used to go to next line....
for (c=0;c<d;c++){
c = a + b;//Doing and printing the fibonacci...
System.out.println(c);
a = b;
b = c;//Swapping the values...
}
}
}
So here i have given you three methods that should give the same output(Most probably) choose whichever is convenient for you..
Look at this code snippet which is much easier than yours to understand. Solution tip is simple, you keep 2 pointers for the first 2 fibonacci numbers and update them appropriately in the loop. In the example below, the loop executes 10 times, you can modify it as desired.
static void fibonacci() {
int ptr1 = 1, ptr2 = 1;
int temp = 0;
System.out.print(ptr1 + " " + ptr2 + " ");
for (int i = 0; i < 10; i++) {
System.out.print(ptr1 + ptr2 + " ");
temp = ptr1;
ptr1 = ptr2;
ptr2 = temp + ptr2;
}
}
Output:
1 1 2 3 5 8 13 21 34 55 89 144
Expanding on the answers, if you want to look really cool use recursion.
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int N = 300; // how many numbers you want to generate
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fib(i));
}
}
Here is Google search of what it is, hope those resources help: http://bit.ly/1cWxhUS
I'm a beginner in java as well however I've found an easy way to create a Fibonacci number using an array. The basic principle of a Fibonacci number is the addition of the current number and the number that came before.
Here is my code:
//Creation of array
int [ ] fib = new int[size];
//Assigning values to the first and second indexes of array named "fib"
fib [0] = 0;
fib [1] = 1;
//Creating variable "a" to use in for loop
int a = 1
//For loop which creates a Fibonacci number
for( int i = 2; i < size ; i++)
{
fib[i] = a;
a = fib[i] + fib[i-1];
}
This is another algorithm which I found online and I kind of simplified the code from it.
public static BigInteger fib(BigInteger x) {
if (x.intValue() < 0){return x.intValue() % 2 == 0 ?fib(x.multiply(BigInteger.valueOf(-1))).multiply(BigInteger.valueOf(-1)) : fib(x.multiply(BigInteger.valueOf(-1)));}
int n = Integer.valueOf(x.toString());
BigInteger a = BigInteger.ZERO,b = BigInteger.ONE;
for (int bit = Integer.highestOneBit(n); bit != 0; bit >>>= 1) {
BigInteger d = a.multiply(b.shiftLeft(1).subtract(a));
BigInteger e = a.multiply(a).add(b.multiply(b));
a = d;
b = e;
if ((n & bit) != 0) {
BigInteger c = a.add(b);
a = b;
b = c;
}
}
return a;
}
I know there is a chance that you wont understand how to use BigInteger, so I am giving you this link, just trying to be helpful.
Here we get Fibonacci Series up to n.
public static void fibSequence(int n) {
int sum = 0;
for (int x = 0, y = 1; sum < n; x = y, y = sum, sum = x + y) {
System.out.print(sum + " ");
}
}
Example:
Input: n = 20
Output: 0 1 1 2 3 5 8 13
more simple way
public static void main(String[] args) {
int first = 1;
int second = 2;
for (int i = 0; i < 20; i++) {
if (i == 0)
System.out.print(first);
System.out.print("," + second);
int temp = second;
second = first + second;
first = temp;
}
}```
program output :: 1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946
import java.util.*;
public class sequence1
{
public static void main(String[] args)
{
sequence1 fs=new sequence1();
fs.fibonacci();
}
public void fibonacci()
{
int numb1 = 1;
int numb2 = 1;
int temp = 0;
#SuppressWarnings("resource")
Scanner input=new Scanner(System.in);
System.out.println("How Many Terms? (Up To 45)");
int x=input.nextInt();
x=x-2;
System.out.println(numb1);
System.out.println(numb2);
for (int i = 0; i < x; i++)
{
System.out.println(numb1 + numb2 + " ");
temp = numb1;
numb1 = numb2;
numb2 = temp + numb2;
}
}
}
This function return the fibonacci series
/**
* #param startElement
* #param secondElent
* #param length :length of fibonacci series
* #return fibonacciseries : contain the series of fibonacci series
*/
public int[] createFibonacciSeries(int startElement, int secondElent,
int length) {
int fibonacciSeries[] = new int[length];
fibonacciSeries[0] = startElement;
fibonacciSeries[1] = secondElent;
for (int i = 2; i < length; i++) {
fibonacciSeries[i] = fibonacciSeries[i - 1]
+ fibonacciSeries[i - 2];
}
return fibonacciSeries;
}
import java.util.*;
class MyFibonacci {
public static void main(String a[]){
int febCount = 15;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i < febCount; i++){
feb[i] = feb[i-1] + feb[i-2];
}
for(int i=0; i< febCount; i++){
System.out.print(feb[i] + " ");
}
}
}
public class FibonacciExercitiu {
public static void main(String[] args) {
int result = fib(6); //here we test the code. Scanner can be implemented.
System.out.println(result);
}
public static int fib(int n) {
int x = 1;
int y = 1;
int z = 1; //this line is only for declaring z as a variable. the real assignment for z is in the for loop.
for (int i = 0; i < n - 2; i++) {
z = x + y;
x = y;
y = z;
}
return z;
}
/*
1. F(0) = 1 (x)
2. F(1) = 1.(y) =>Becomes x for point4
3.(z)F(2) = 2 (z) =>Becomes Y for point4 // becomes X for point 5
4.(z)F(3) = 3 // becomes y for point 5
5.(z)F(4) = 5 ..and so on
*/
}
public static int[] fibonachiSeq(int n)
{
if (n < 0)
return null;
int[] F = new int[n+1];
F[0] = 0;
if (n == 0)
return F;
F[1] = 1;
for (int i = 2; i <= n; i++)
{
F[i] = F[i-1] + F[i-2];
}
return F;
}
Using while loop
class Feb
{
static void Main(string[] args)
{
int fn = 0;
int sn = 1;
int tn = 1;
Console.WriteLine(fn);
Console.WriteLine(sn);
while (true)
{
tn = fn + sn;
if (tn >10)
{
break;
}
Console.WriteLine(tn);
fn = sn;
sn = tn;
}
Console.Read();
}
}
public class Febonacci {
public static void main(String[] args) {
int first =0;
int secend =1;
System.out.print(first+","+secend);
for (int k=1;k<7;k++){
System.out.print(","+(first+secend ));
if(k%2!=0)
first+=secend;
else
secend+=first;
}
}
}
public class FibonacciSeries {
public static void main(String[] args) {
int a=0, c=0, b=1;
for(int i=0; i<10; i++) {
System.out.print(c+" ");
a = c + b;
c = b;
b = a;
}
}
}