Jump to content

Find the number of all daffodils in a certain range

Programmer Frank

Write a program to find all daffodils in a certain range. The so-called daffodil number refers to a three-digit number whose cube sum is exactly equal to the number itself. For example, 153 = 1 × 1 × 1 + 5 × 5 × 5 + 3 × 3 × 3. Tip: For a three-digit number, first find its hundreds, tens, and single digits, and then use the characteristics of the daffodil number to make a judgment.

Link to comment
Share on other sites

Link to post
Share on other sites

const checkDaffodil = (num: number) => {
  if(typeof num !== 'number') {
    return false;
  }
  
  const parts = num.toString().split('');
  
  let sum = 0;
  
  parts.forEach((part: number) => {
  	sum += Math.pow(parseInt(part), 3);	
  });
  
  return sum === num;
} 

console.log(checkDaffodil(153)); // True

Too early in the morning for this haha

Link to comment
Share on other sites

Link to post
Share on other sites

Or C#

int from = 1;
int to = 6000;
List<int> daffodils = Enumerable.Range(from, to).Where(num => num.ToString().Sum(s => Math.Pow(Convert.ToDouble(s.ToString()), 3)) == num).ToList();

 

Link to comment
Share on other sites

Link to post
Share on other sites

php , function to determine if the number is good or not.

You can extend it with a for to check all numbers within a range.

 

<?php
function test_number($value) {
	$digits = array();
	$nr = $value;
	while ($nr>0) {
		$rest = $nr % 10;
		$nr = intdiv($nr, 10);
		array_push($digits,$rest);
	}
	//var_dump($digits);
	// array will have the individual digits in reverse order ex: 153 => 3, 5, 1 
	if (count($digits) != 3) return FALSE; // only consider valid numbers that have 3 digits.
	if (($digits[0]**3 + $digits[1]**3 + $digits[2]**3) == $value) return TRUE;
	return FALSE; 
}

var_dump(test_number(153));

?>

 

Note that a clever algorithm would not just brute force by checking all possible combinations.

You have some shortcuts... you can pre-calculate the cube of all numbers between 0 and 9 and just add them when making combinations and do other clever things.

 

<?php

$powers = array();
for ($i=0;$i<10;$i++) $powers[$i] = $i**3;

for ($k=0;$k<10;$k++) {
	for ($j=0;$j<10;$j++) {
		for ($i=1;$i<10;$i++) { // start from 1, because you want min 100
			$number = $i*100+$j*10+$k;
			$total = $powers[$i] + $powers[$j] + $powers[$k];
			if ($number == $total) echo $number."\n";
		}
	}
}

?>

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×