i wrote a program to display fibonacci series in java but now i want the numbers in the sequence to be displayed in tens that is the first ten fibonacci numbers on one line followed by the next ten on the next line and so.....
i have been having real problems making that possible.
this is the program:
import java.util.Scanner;
import java.math.BigInteger;
class Fibonacci {
public static void main(String args[]) {
System.out.print("Enter number upto which Fibonacci series to print: ");
int number = new Scanner(System.in).nextInt();
System.out.println("\n\nFibonacci series upto " + number + " numbers : ");
for (int i = 1; i <= number; i++) {
System.out.println(fibonacciLoop(i) + " ");
}
}
public static BigInteger fibonacciLoop(int number) {
if (number == 1 || number == 2) {
return BigInteger.valueOf(1);
}
for (int x = 1; x <= number; x++){
return BigInteger.valueOf(x);
}
BigInteger fibonacci = BigInteger.valueOf(1);
BigInteger fibo1 = BigInteger.valueOf(1);
BigInteger fibo2 = BigInteger.valueOf(1);
for (int i = 3; i <= number; i++) {
fibonacci = fibo1.add(fibo2);
fibo1 = fibo2;
fibo2 = fibonacci;
}
return fibonacci;
}
}
print (don't println) each number to have them on the same line. And whenever your counter i is a multiple of 10, start a new line.
for (int i = 1; i <= number; i++) {
System.out.print(fibonacciLoop(i) + " ");
if (i % 10 == 0)
System.out.println();
}
if(i % 10 == 0)
{
System.out.println();
}
Or if you wanted to be fancy.
System.out.print(fibonacciLoop(i) + " " + (i % 10 == 0? "\n":""));
Note that your fibonaci calculation does not work due to the following for loop:
for (int x = 1; x <= number; x++){
return BigInteger.valueOf(x);
}
The follow will do what you requested:
import java.math.BigInteger;
import java.util.Scanner;
import java.util.LinkedList;
public class Test {
Test(int number) {
System.out.println("\n\nFibonacci series upto " + number + " numbers : ");
LinkedList<BigInteger> list = new LinkedList<BigInteger>();
for (int i = 1; i <= number; i++) {
list.add(fibonacciLoop(i));
if(list.size() == 10) {
printFibo(list);
list = new LinkedList<BigInteger>();
}
}
if(!list.isEmpty()) printFibo(list);
}
public static void main(String args[]) {
System.out.print("Enter number upto which Fibonacci series to print: ");
new Test(new Scanner(System.in).nextInt());
}
private void printFibo(LinkedList<BigInteger> list) {
for(BigInteger fiboNumber : list) {
System.out.print(fiboNumber + " ");
}
System.out.println("");
}
public BigInteger fibonacciLoop(int number) {
if (number == 1 || number == 2) {
return BigInteger.valueOf(1);
}
BigInteger fibonacci = BigInteger.valueOf(1);
BigInteger fibo1 = BigInteger.valueOf(1);
BigInteger fibo2 = BigInteger.valueOf(1);
for (int i = 3; i <= number; i++) {
fibonacci = fibo1.add(fibo2);
fibo1 = fibo2;
fibo2 = fibonacci;
}
return fibonacci;
}
}
Related
what's wrong with this?
if condition is not executing.
import java.util.Scanner;
public class ArmstrongNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("ENTER THE NUMBER");
int n = sc.nextInt();
int temp = n;
int rem = 0;
int sum = 0;
while (n != 0) {
rem = n % 10;
sum = sum + (rem * rem * rem);
n = n / 10;
}
if (temp == n) {
System.out.println("number is a AMSTRONG");
} else {
System.out.println("NUMBER IS NOT AMSTRONG");
}
}
}
Your logic is wrong. if(temp==n) { is after while(n!=0) { so the only way it could be true is if temp == 0.
Your Calcualtion is fine but your compare is wrong. For example the number 153, which is a armstrong number, your variables will have the following values at the end of the loop:
temp = 153
rem = 1
sum = 153
n = 0
So you should not compare temp to n temp == n , how you currently do but temp to sum temp == sum
Also take in mind that your check will only work for three digits numbers, because your power is allways three. So for other armstrong numbers it simply won't work, for example:
54748 = 55 + 45 + 75 + 45 + 85 = 3125 + 1024 + 16807 + 1024 + 32768
In this solution i used the Math libary and the power but there are more ways if you don't like this to calc the length of an number
public class ArmstrongNum {
private static final Scanner SC = new Scanner(System.in);
private static boolean isArmstrongNumber(int n){
int temp = n;
int rem;
int length = (int) (Math.log10(n) + 1);
int sum = 0;
while (n != 0) {
rem = n % 10;
sum = sum + (int) Math.pow(rem, length);
n = n / 10;
}
return temp == sum;
}
public static void main(String[] args) {
System.out.print("ENTER THE NUMBER: ");
int n = SC.nextInt();
if (isArmstrongNumber(n)) {
System.out.printf("%d is a Armstrong number", n);
} else {
System.out.printf("%d is no Armstrong number", n);
}
}
}
Try another way
public static void main(String[] args) {
try {
Scanner sc= new Scanner(System.in);
System.out.println("ENTER THE NUMBER");
int n = sc.nextInt();
if (n == 0) {
throw new Exception("Number is 0");
}
int sum = 0;
String number = String.valueOf(n);
char[] chars = number.toCharArray();
double length = chars.length;
for (char item : chars) {
double result = Math.pow(Double.parseDouble(String.valueOf(item)), length);
sum = sum + (int) result;
}
if (sum == n ) {
System.out.println("number is a AMSTRONG");}
else {
System.out.println("NUMBER IS NOT AMSTRONG");
}
} catch (Exception exception) {
System.out.println(exception.getMessage());
}
}
I will get to the point quickly. Basically smith numbers are: Composite number the sum of whose digits is the sum of the digits of its prime factors (excluding 1). (The primes are excluded since they trivially satisfy this condition). One example of a Smith number is the beast number 666=2·3·3·37, since 6+6+6=2+3+3+(3+7)=18.
what i've tried:
In a for loop first i get the sum of the current number's(i) digits
In same loop i try to get the sum of the number's prime factors digits.
I've made another method to check if current number that is going to proccessed in for loop is prime or not,if its prime it will be excluded
But my code is seems to not working can you guys help out?
public static void main(String[] args) {
smithInrange(1, 50);
}
public static void smithInrange(int start_val, int end_val) {
for (int i = start_val; i < end_val; i++) {
if(!isPrime(i)) { //since we banned prime numbers from this process i don't include them
int for_digit_sum = i, digit = 0, digit_sum = 0, for_factor_purpose = i, smith_sum = 0;
int first = 0, second = 0, last = 0;
// System.out.println("current number is" + i);
while (for_digit_sum > 0) { // in this while loop i get the sum of current number's digits
digit = for_digit_sum % 10;
digit_sum += digit;
for_digit_sum /= 10;
}
// System.out.println("digit sum is"+digit_sum);
while (for_factor_purpose % 2 == 0) { // i divide the current number to 2 until it became an odd number
first += 2;
for_factor_purpose /= 2;
}
// System.out.println("the first sum is " + first);
for (int j = 3; j < Math.sqrt(for_factor_purpose); j += 2) {
while (for_factor_purpose % j == 0) { // this while loop is for getting the digit sum of every prime
// factor that j has
int inner_digit = 0, inner_temp = j, inner_digit_sum = 0;
while (inner_temp > 0) {
inner_digit = inner_temp % 10;
second += inner_digit;
inner_temp /= 10;
}
// System.out.println("the second sum is " + second);
for_factor_purpose /= j;
}
}
int last_temp = for_factor_purpose, last_digit = 0, last_digit_sum = 0;
if (for_factor_purpose > 2) {
while (last_temp > 0) {
last_digit = last_temp % 10;
last += last_digit;
last_temp /= 10;
}
// System.out.println("last is " + last);
}
smith_sum = first + second + last;
// System.out.println("smith num is "+ smith_sum);
// System.out.println(smith_sum);
if (smith_sum == digit_sum) {
System.out.println("the num founded is" + i);
}
}
}
}
public static boolean isPrime(int i) {
int sqrt = (int) Math.sqrt(i) + 1;
for (int k = 2; k < sqrt; k++) {
if (i % k == 0) {
// number is perfectly divisible - no prime
return false;
}
}
return true;
}
the output is:
the num founded is4
the num founded is9
the num founded is22
the num founded is25
the num founded is27
the num founded is49
how ever the smith number between this range(1 and 50) are:
4, 22 and 27
edit:I_ve found the problem which is :
Math.sqrt(for_factor_purpose) it seems i should add 1 to it to eliminate square numbers. Thanks to you guys i've see sthe solution on other perspectives.
Keep coding!
Main loop for printing Smith numbers.
for (int i = 3; i < 10000; i++) {
if (isSmith(i)) {
System.out.println(i + " is a Smith number.");
}
}
The test method to determine if the supplied number is a Smith number. The list of primes is only increased if the last prime is smaller in magnitude than the number under test.
static boolean isSmith(int v) {
int sum = 0;
int save = v;
int lastPrime = primes.get(primes.size() - 1);
if (lastPrime < v) {
genPrimes(v);
}
outer:
for (int p : primes) {
while (save > 1) {
if (save % p != 0) {
continue outer;
}
sum += sumOfDigits(p);
save /= p;
}
break;
}
return sum == sumOfDigits(v) && !primes.contains(v);
}
Helper method to sum the digits of a number.
static int sumOfDigits(int i) {
return String.valueOf(i).chars().map(c -> c - '0').sum();
}
And the prime generator. It uses the list as it is created to determine if a given
number is a prime.
static List<Integer> primes = new ArrayList<>(List.of(2, 3));
static void genPrimes(int max) {
int next = primes.get(primes.size() - 1);
outer:
while (next <= max) {
next += 2;
for (int p : primes) {
if (next % p == 0) {
continue outer;
}
if (p * p > next) {
break;
}
}
primes.add(next);
}
}
}
I do not want to spoil the answer finding, but just some simpler code snippets,
making everything simpler, and more readable.
public boolean isSmith(int a) {
if (a < 2) return false;
int factor = findDivisor(a);
if (factor == a) return false;
int sum = digitSum(a);
// loop:
a /= factor;
sum -= digitSum(factor);
...
}
boolean isPrime(int a){
for(int i = 2; i*i <= a; i++) {
if (a % i == 0) {
return false;
}
}
return true;
}
int findDivisor(int a){
for(int i = 2; i*i <= a; i++) {
if (a % i == 0) {
return i;
}
}
return a;
}
int digitSum(int a) {
if (a < 10) {
return a;
}
int digit = a % 10;
int rest = a / 10;
return digit + digitSum(rest);
}
As you see integer division 23 / 10 == 2, and modulo (remainder) %: 23 % 10 == 3 can simplify things.
Instead of isPrime, finding factor(s) is more logical. In fact the best solution is not using findDivisor, but immediately find all factors
int factorsSum = 0;
int factorsCount = 0;
for(int i = 2; i*i <= a; i++) {
while (a % i == 0) {
factorsSum += digitSum(i);
a /= i;
factorsCount++;
}
}
// The remaining factor >= sqrt(original a) must be a prime.
// (It cannot contain smaller factors.)
factorsSum += digitSum(a);
factorsCount++;
Here is the code. If you need further help, please let me know. The code is pretty self explanatory and a decent bit was taken from your code but if you need me to explain it let me know.
In short, I created methods to check if a number is a smith number and then checked each int in the range.
import java.util.*;
public class MyClass {
public static void main(String args[]) {
System.out.println(smithInRange)
}
public int factor;
public boolean smithInRange(int a, int b){
for (int i=Math.min(a,b);i<=Math.max(a,b);i++) if(isSmith(i)) return true;
return false;
}
public boolean isSmith(int a){
if(a<2) return false;
if(isPrime(a)) return false;
int digits=0;
int factors=0;
String x=a+¨" ";
for(int i=0;i<x.length()-1;i++) digits+= Integer.parseInt(x.substring(i,i+1));
ArrayList<Integer> pF = new ArrayList<Integer>();
pF.add(a);
while(!aIsPrime(pF)){
int num = pF.get(pF.size-1)
pF.remove(pF.size()-1);
pF.add(factor);
pF.add(num/factor)
}
for(int i: pF){
if((factors+"").length()==1)factors+= i;
else{
String ss= i+" ";
int nums=0;
for(int j=0;j<ss.length()-1;j++){
nums+=Integer.parseInt(ss.substring(j,j+1));
}
}
}
return (factors==digits);
}
public boolean isPrime(int a){
for(int i=2;i<=(int)Math.sqrt(a),i++){
String s = (double)a/(double)i+"";
if(s.substring(s.length()-2).equals(".0")){
return false;
factor = i;
}
}
return true;
}
public boolean aIsPrime(ArrayList<int> a){
for(int i: a) if (!isPrime(a)) return false;
return true;
}
}
I'm having issues getting all prime numbers between a given integer A and integer B.
The issue is that the output goes well beyond whatever I defined for B. I thought that the
if (isPrime){
count++;
would fix this but the output still goes well beyond the intended number of integer B.
For example if int valueA = 1 and int valueB = 100, it'll get prime numbers from around 1 to 500 before stopping, instead of just ending the check at 100.
Thank you for any assistance.
import java.util.*;
public class PrimeNumbersTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
// Ask user to input an integer value for A and B
System.out.print("Enter the value of A (must be an integer): ");
int valueA = input.nextInt();
System.out.print("Enter the value of B (must be an integer): ");
int valueB = input.nextInt();
System.out.println("The prime numbers between " + valueA + " and " + valueB + " are:");
final int LINE = 10;
int count = valueA;
int number = 2;
while (count < valueB) {
// Assume the number is prime
boolean isPrime = true;
// Test if number is prime
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) { // If true number is not prime
isPrime = false; // Set isPrime to false
break; // Exit the for loop
}
}
if (isPrime) {
count++;
if (count % LINE == 0) {
System.out.println(number);
}
else
System.out.print(number + " ");
}
number++;
}
}
}
When you want to work on a range of number, use a for loop instead of while loop to reduce confusion. You obviously want
for(int number = valueA; number <= valueB; number++){/*check if number is prime*/}
Example:
public static void main(String []args){
int valueA = 1;
int valueB = 100;
int count = 0;
for(int number = valueA; number <= valueB; number++)
{
if(isPrime(number))
{
count++;
System.out.println(number);
}
}
System.out.println("count = " + count);
}
public static boolean isPrime(int n)
{
for(int i = 2; i*i <= n; i++)
{
if(n % i == 0)
{
return false;
}
}
return n > 1;
}
For your requirement of checking isPrime inline:
public static void main(String []args){
int valueA = 1;
int valueB = 100;
int count = 0;
for(int number = valueA; number <= valueB; number++)
{
boolean isPrime = number > 1;
for(int i = 2; i*i <= number; i++)
{
if(number % i == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
{
count++;
System.out.println(number);
}
}
System.out.println("count = " + count);
}
I have the below java program which prints all the prime numbers till 100, now I want to modify the same so that user will enter the number and it will print not the range but the very last prime number exists in that range, please advise how to modify the below program also I want to change the return type from string to int that is
class PrimeNumbers
{
public static void main (String[] args)
{
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
for (i = 1; i <= 100; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to 100 are :");
System.out.println(primeNumbers);
}
}
right now the output is
Prime numbers from 1 to 100 are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
and I want only last prime number to be printed only
100
Try just maintaining state for the most recent prime number discovered by the loop:
public static void main (String[] args) {
int i = 0;
int num = 0;
int prime;
for (i = 1; i <= 100; i++) {
int counter = 0;
for (num = i; num >= 1; num--) {
if (i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
prime = i;
}
}
System.out.println("Last prime number from 1 to 100 is: " + prime);
}
The proposed source codes can be written more structured:
public class PrimeNumbers {
private static boolean isPrime(int n) {
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i = 3; i <= Math.sqrt(n); i = i + 2)
if (n % i == 0) return false;
return true;
}
public static void main(String[] args) {
int biggestPrimeNumber = 0;
String primeNumbers = "";
for (int n = 2; n <= 100; n++)
if (isPrime(n)) {
biggestPrimeNumber = n;
//Appended the Prime number to the String
primeNumbers += n + " ";
}
System.out.println("Prime numbers from 1 to 100 are: " + primeNumbers);
System.out.println("Last prime number from 1 to 100 is: " + biggestPrimeNumber);
}
}
For checking the primality of a number there are many algorithms like Miller–Rabin primality test but a simple brute force way is to check numbers up to sqrt of the desired number.
You might want to introduce a int variable (int primeNumber) that will hold the value of the largest prime number. Made some minor changes in problem code:
int i = 0;
int num = 0;
//Empty String
int primeNumber = 0;
for (i = 1; i <= 100; i++) {
int counter=0;
for(num =i; num>=1; num--) {
if(i%num==0) {
counter = counter + 1;
}
}
if (counter ==2) {
primeNumber = i;
}
}
System.out.println("Largest Prime number from 1 to 100 is : ");
System.out.println(primeNumber);
As per my understanding ,you want to print the max prime number which is closed to 100.
class PrimeNumbers
{
public static void main (String[] args)
{
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
for (i = 1; i <= 100; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = i+ "";
}
}
System.out.println("Max prime number between 1 to 100 is:");
System.out.println(primeNumbers);
}
}
UPDATE :
This program can be further optimized to improvise time complexity
public class PrimeNumbers{
public static void main (String[] args)
{
int i =0;
int num =0;
int primeNumbers = 0;
for (i = 100; i >= 1; i--)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
primeNumbers = i;
break;
}
}
System.out.println("Max prime number between 1 to 100 is:");
System.out.println(primeNumbers);
}
}
Twin primes are a pair of prime numbers that differ by 2. For example, 3 and 5 are twin primes, 5 and
7 are twin primes, and 11 and 13 are twin primes. Write a Java program TwinPrimes.java that prompts
the user to input the search range of twin primes, display all the twin primes (2 pairs per line) within
the range, and print the number of twin primes found. The search range is assumed to be positive and
your program should repeatedly perform the same task until a sentinel value of -1 is entered.
The expected output of your program should be as follows:
Round 1:
Enter the search range: 100
(3,5) (5,7)
(11,13) (17,19)
(29,31) (41,43)
(59,61) (71,73)
Number of twin primes less than or equal to 100 is 8
Round 2:
Enter the search range: 150
(3,5) (5,7)
(11,13) (17,19)
(29,31) (41,43)
(59,61) (71,73)
......(Omitted)
Number of twin primes less than or equal to 200 is 15
Round 4:
Enter the search range: -1
End
I know that I am not complected the code, but I am struggling on how to print the Prime numbers in ( , ) ( , )way and how to calculate the number of twin primes show it at the end.
The below coding is what I had to do:
import java.util.Scanner;
import java.util.Random;
public class TwinPrimes {
public static void main(String[] args) {
int i = 0;
int A, B = 0, D = 0;
int num = 0;
System.out.println("Round" + " " + ++i + ":");
Scanner scn = new Scanner(System.in);
System.out.print("Enter the search range:");
A = scn.nextInt();
{
if (A < 0)
System.out.println("End");
}
for (i = 3; i <= A; i++) {
int counter = 0;
for (num = B; num >= 1; num--) {
{
if (B % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
}
}
System.out.println("(" + i + "," + i + ")" + " " + "(" + i + "," + i + ")");
// sum Number of twin primes to
System.out.println("Number of twin primes less than or equal to " + A + " " + "is" + " ");
return;
}
}
}
package array1;
import java.io.IOException;
import java.util.Scanner;
public class Mainclass {
public static void main(String args[]) throws NumberFormatException, IOException
{
int a,k=0,line=0,count=0;
while(true)
{
System.out.println("Round" + " " + ++k + ":");
Scanner scn = new Scanner(System.in);
System.out.print("Enter the search range:");
a= scn.nextInt();
{
if (a< 0)
{
System.out.println("End");
System.exit(0);
}
}
System.out.println("The Twin Prime Numbers within the given range are : ");
for(int i=2; i<=(a-2); i++)
{
if(isPrime(i) == true && isPrime(i+2) == true)
{
System.out.print("("+i+","+(i+2)+") ");
line++;
if(line==2)
{
System.out.println();
line=0;
}
count++;
}
}
System.out.println();
System.out.println("the number of twin prime numbers less than or equal to"+a+"is"+count);
}
}
static boolean isPrime(int n) //funton for checking prime
{
int count=0;
for(int i=1; i<=n; i++)
{
if(n%i == 0)
count++;
}
if(count == 2)
return true;
else
return false;
}
}
I am struggling on how to print the Prime numbers in ( , ) ( , ) way
You may use String.format. See How to use String.format in Java?
For example, String.format("Found pair (%d,%d)", prime1, prime2);
How to calculate the number of twin primes show it at the end.
Simply keep a counter, say int counter when you're looking for the prime pairs.
import java.util.Scanner;
public class Main {
// Consider writing a helper function to check primality
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
for (int i = 2; i <= Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int max_number = 100;
int counter = 0; // keep a count
for (int i = 2; i+2 < max_number; i++) {
if (isPrime(i) && isPrime(i+2)) {
counter++; // increment counter
String msg = String.format("Found pair (%d,%d)", i, i+2);
System.out.println(msg);
}
}
System.out.println("Total number of pairs is " + counter);
// Total number of pairs is 8
}
}