I have this part of my code done, and I am trying to get it to print just the last Fibonacci Number, not all of them. How should I go about doing this? I know that the whole program isn't completed yet, but I just need to know how to print the last number for instance, when you select choice 1, then type "30" for index you should only get an output of 832040 instead of every fibonacci number to 30. Thanks!
import java.util.Scanner;
public class Fibonacci {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("This is a Fibonacci sequence generator");
System.out.println("Choose what you would like to do");
System.out.println("1. Find the nth Fibonacci number");
System.out.println("2. Find the smallest Fibonacci number that exceeds user given value");
System.out.println("3. Find the two Fibonacci numbers whose ratio is close enough to the golden number");
System.out.print("Enter your choice: ");
int choice = scan.nextInt();
int xPre = 0;
int xCurr = 1;
int xNew;
switch (choice)
{
case 1:
System.out.print("Enter the target index to generate (>1): ");
int index = scan.nextInt();
for (int i = 2; i<=index; i++)
{xNew = xPre + xCurr;
xPre = xCurr;
xCurr = xNew;
System.out.println("The " + index + "th number Fibonacci number is " + xNew);
}
}}}
Basically just modify the code as below
switch (choice)
{
case 1:
System.out.print("Enter the target index to generate (>1): ");
int index = scan.nextInt();
for (int i = 2; i<=index; i++)
{xNew = xPre + xCurr;
xPre = xCurr;
xCurr = xNew;
}
System.out.println("The " + index + "th number Fibonacci number is " + xNew);
Since the xNew Variable is last modified to hold the value of the index ( eg - 30 ) it should show the final value as 832040 alone.
Related
I created a function to calculate the selling price of an item. Each year, the price of the item will decrease by 3/4 of its original price. The problem with my function is it doesn't want to read the year variable regardless of its value. My function always returns 60000000. Can someone please tell me what's wrong with it?
int add(double year, double price) {
int i = 0;
while (i < year) {
double final_price = price * 3 / 4;
i++;
return final_price.round();
}
}
void main(List<String> arguments) {
double x = 3;
double y = 80000000;
int result = add(x, y);
print(result);
}
int add(double year, double price) {
int i = 0;
double final_price=price; // change 1
while (i < year) {
final_price = final_price* 3 / 4; // change 2
i++;
}
return final_price.round(); // change 3
}
void main(List<String> arguments) {
double x = 3;
double y = 80000000;
int result = add(x, y);
print(result);
}
Here you go. Returning a value from inside the while loop will stop the function execution on the first traversal only.
Also you need to make final price equal to price because final_price's value is not being changed as price remains same and i increases.
what actually are you to trying to do ?
I fixed your code
int add(double year, double price) {
int i = 0;
double final_price = 0 ;
while (i < year) {
double f = price * 3 / 4;
i++;
final_price = f ;
}
return final_price.round();
}
void main() // you try to pass an arguments that never used I remove it
{
double x = 3;
double y = 800000;
int result = add(x, y);
print(result);
}
I am trying to solve 445. Add Two Numbers II from LeetCode where it is asked:
Given two non-empty linked lists representing two non-negative integers, add the two numbers and return it as a linked list. The most significant digit comes first and each of their nodes contain a single digit.
For some test cases, I am getting negative number from the sum method that I have implemented. I think it is impossible to get any negative digit in my code. Can you help me finding the bug?
Below is the code that I tried:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//ListNode previous = null;
int len1 = 0;
int len2 = 0;
ListNode head1 = l1;
ListNode head2 = l2;
while(l1!=null){
len1++;
l1=l1.next;
}
while(l2!=null){
len2++;
l2=l2.next;
}
int sum=0;
if (len1 >= len2){
sum= sum(head1,head2,len1,len2);
}else{
sum= sum(head2,head1,len2,len1);
}
String sumString = "" + sum;
ListNode extraHead = new ListNode(1);
ListNode copy = extraHead;
for(int i = 0;i<sumString.length();i++){
ListNode bit = new ListNode(Integer.parseInt(String.valueOf(sumString.charAt(i))));//Integer.parseInt(String.valueOf(sumString.charAt(i)))
extraHead.next = bit;
extraHead = extraHead.next;
}
return copy.next;
}
public int sum(ListNode l1, ListNode l2, int len1, int len2){
int diff = 0;
int resLen = 0;
diff = len1 - len2;
resLen = len1;
int[] res = new int[resLen];
ListNode fast = l1;
ListNode slow = l2;
for(int count = 0; count<diff; count++){
res[count] = fast.val;
fast = fast.next;
}
for(int count = diff;count < res.length;count++){
res[count] = fast.val + slow.val;
fast=fast.next;
slow=slow.next;
}
int sum = 0;
for(int i = len1;i>0;i-- ){
sum = sum + res[len1-i] * (int)Math.pow(10,i-1);
}
return sum;
}
}
Here is the error message that I get:
Error Details
java.lang.NumberFormatException: For input string: "-"
at line 68, java.base/java.lang.NumberFormatException.forInputString
at line 648, java.base/java.lang.Integer.parseInt
at line 776, java.base/java.lang.Integer.parseInt
at line 41, Solution.addTwoNumbers
at line 54, __DriverSolution__.__helper__
at line 87, __Driver__.main
Here is the input causing the error:
[3,9,9,9,9,9,9,9,9,9]
[7]
I want to generate a random six-digit number. I tried to use the Random class, but new Random().nextInt(999999) generates some numbers with less than six digits.
So you want just the numbers 100000 to (and including) 999999.
you can get a random number in this range (900000) and add 100000 to the random number you get:
var rng = new Random();
var code = rng.nextInt(900000) + 100000;
This will always give you a random number with 6 digits.
void main() {
var rnd = new math.Random();
var next = rnd.nextDouble() * 1000000;
while (next < 100000) {
next *= 10;
}
print(next.toInt());
}
you can also generate 6 different numbers and then concatenate them in one string and convert it to integer if you want
import 'dart:math';
main(){
var rndnumber="";
var rnd= new Random();
for (var i = 0; i < 6; i++) {
rndnumber = rndnumber + rnd.nextInt(9).toString();
}
print(rndnumber);
}
Here is a Dart extension method that will generate a non-negative random integer with a specified number of digits:
extension RandomOfDigits on Random {
/// Generates a non-negative random integer with a specified number of digits.
///
/// Supports [digitCount] values between 1 and 9 inclusive.
int nextIntOfDigits(int digitCount) {
assert(1 <= digitCount && digitCount <= 9);
int min = digitCount == 1 ? 0 : pow(10, digitCount - 1);
int max = pow(10, digitCount);
return min + nextInt(max - min);
}
}
In your case use it like this:
final random = Random();
print(random.nextIntOfDigits(6));
The following class will generate an integer with 'n' digits, or a string with 'n' digits.
The numeric method will be much faster, but is limited in the number of digits.
import 'dart:math';
class RandomDigits {
static const MaxNumericDigits = 17;
static final _random = Random();
static int getInteger(int digitCount) {
if (digitCount > MaxNumericDigits || digitCount < 1) throw new RangeError.range(0, 1, MaxNumericDigits, "Digit Count");
var digit = _random.nextInt(9) + 1; // first digit must not be a zero
int n = digit;
for (var i = 0; i < digitCount - 1; i++) {
digit = _random.nextInt(10);
n *= 10;
n += digit;
}
return n;
}
static String getString(int digitCount) {
String s = "";
for (var i = 0; i < digitCount; i++) {
s += _random.nextInt(10).toString();
}
return s;
}
}
void main() {
print(RandomDigits.getInteger(6));
print(RandomDigits.getString(36));
}
Output:
995723
198815207332880163668637448423456900
If you want to get 6 digit value from 0 to 999999, you can add leading 0 if the number is less than 6 digits.
String r = Random().nextInt(999999).toString().padLeft(6, '0');
// example output: 025328
i had the same problem.although there are 3-4 ways to tackle it but i find the below one simple and sorted.
simply check for the number of length match. find below code
Integer otp = new Random().nextInt(999999);
int noOfOtpDigit=6;
while(Integer.toString(otp).length()!=noOfOtpDigit) {
otp = new Random().nextInt(999999);
}
String otpString = String.valueOf(otp);
import 'dart:math';
void main() {
print(get6DigitNumber());
}
String get6DigitNumber(){
Random random = Random();
String number = '';
for(int i = 0; i < 6; i++){
number = number + random.nextInt(9).toString();
}
return number;
}
Here is your unlimited supply of six-digit random numbers
String getRandomNumber(){
final r = Random();
return List<int>.generate(6, (index) => r.nextInt(10)).fold<String>("", (prev, i) => prev += i.toString());
}
This is working for me in C#.
Random random = new Random();
string elementIndex = random.Next(100000, 999999).ToString();
I wrote this code to determine which numbers between two numbers someone types are prime and which are composite. The user types two numbers, e.g. 5 & 10, and in that case the program should output:
5 is prime
6 is not prime
7 is prime
8 is not prime
9 is not prime
10 is not prime
But it is not doing this correctly. For example, if the user enters 13 and 33, the output is that 13, 14, and 15 are prime, but all the other numbers are not. What's even more strange is that the results contradict each other. For example, if the user enters 10 and 20, the program outputs that all the numbers are not prime.
package more.basic.applications;
import java.util.Scanner;
public class MoreBasicApplications {
public static void main(String[] args)
{
//program to determine how many numbers between 2 numbers inclusive are prime, and how many are composite, as well as display them
int j = 2;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter number 1, between 0 and 100: ");
int number = reader.nextInt();
boolean composite = false;
System.out.println("Please enter number 2, between 0 and 200: ");
int number2 = reader.nextInt();
int difference = number2 - number;
int[] array = new int[difference+1];
for (int i = 0; i < array.length; i++)
{
array[i] = number + i;
while (j <= Math.sqrt(array[i]))
{
if (array[i]%j == 0) {
composite = true;
}
j++;
}
if (composite == true) {
System.out.println (array[i] + " is not prime.");
}
else
{
System.out.println (array[i] + " is prime.");
}
}
}
It looks like you don't "reset" j back to 2 at the beginning of your for loop, so j keeps getting bigger and bigger.
for (int i = 0; i < array.length; i++) {
j = 2; // reset j back to 2.
array[i] = number + i;
while (j <= Math.sqrt(array[i])) {
if (array[i]%j == 0) {
composite = true;
}
j++;
}
if (composite == true) {
System.out.println (array[i] + " is not prime.")
} else {
System.out.println (array[i] + " is prime.");
}
}
How does one get a random number within a range similar to c# Random.Next(int min, int max);
import 'dart:math';
final _random = new Random();
/**
* Generates a positive random integer uniformly distributed on the range
* from [min], inclusive, to [max], exclusive.
*/
int next(int min, int max) => min + _random.nextInt(max - min);
Range can be found with a simple formula as follows
Random rnd;
int min = 5;
int max = 10;
rnd = new Random();
r = min + rnd.nextInt(max - min);
print("$r is in the range of $min and $max");
You can achieve it via Random class object random.nextInt(max) . The nextInt() method requires a max limit. The random number starts from 0 and the max limit itself is exclusive.
import 'dart:math';
Random random = new Random();
int randomNumber = random.nextInt(100); // from 0 upto 99 included
If you want to add the min limit, add the min limit to the result
int randomNumber = random.nextInt(90) + 10; // from 10 upto 99 included
This is really late, but this for anyone who still has the question.
The easiest way to get a random number between a min and a max is the following :
import 'dart:math';
int max = 10;
int randomNumber = Random().nextInt(max) + 1;
The math module in dart has a function called nextInt. This will return an integer from 0 (including 0 ) to max - 1 ( exluding max ). I want a number 1 to 10, hence I add 1 to the nextInt result.
Generates a random integer uniformly distributed in the
range from [min] to [max], both inclusive.
int nextInt(int min, int max) => min + _random.nextInt((max + 1) - min);
It can be achieved exactly as you intended by creating extension on int to get random int value. For example:
import 'dart:math';
import 'package:flutter/foundation.dart';
extension RandomInt on int {
static int generate({int min = 0, #required int max}) {
final _random = Random();
return min + _random.nextInt(max - min);
}
}
And you can use this in your code like so:
List<int> rands = [];
for (int j = 0; j < 19; j++) {
rands.add(RandomInt.generate(max: 50));
}
Note that static extension methods can't be called on type itself (e.g. int.generate(min:10, max:20)), but instead you have to use extension name itself, in this example RandomInt. For detailed discussion, read here.
import 'dart:math';
Random rnd = new Random();
// Define min and max value
int min = 1, max = 10;
//Getting range
int num = min + rnd.nextInt(max - min);
print("$num is in the range of $min and $max");
To generate a random double within a range, multiply a random int with a random double.
import 'dart:math';
Random random = new Random();
int min = 1, max = 10;
double num = (min + random.nextInt(max - min)) * random.nextDouble();
To Generate a random positive integer between a given range:
final _random = new Random();
// from MIN(inclusive), to MAX(exclusive).
int randomBetween(int min, int max) => min + _random.nextInt(max - min);
// from MIN(inclusive), to MAX(inclusive).
int randomBetween(int min, int max) => min + _random.nextInt((max+1) - min);
// from MIN(exclusive), to MAX(exclusive).
int randomBetween(int min, int max) => (min+1) + _random.nextInt(max - (min+1));
When I was making a Tetris game, I had to rotate the x-axis. For this, I wrote the following codes.
I hope it will be useful for you too:
Random rnd = Random();
int min = 0;
int max = 23;
class Block {
int x = min + rnd.nextInt(max - min);
}
A simpler way of doing this is to use the nextInt method within Random:
// Random 50 to 100:
int min = 50;
int max = 100;
int selection = min + (Random(1).nextInt(max-min));
https://api.dartlang.org/stable/2.0.0/dart-math/Random-class.html